excel data uploading is not working in sql database - c#-3.0

This is pradeep
This is the code of the excel uploading to sql database
protected void btnupload_Click ( object sender, EventArgs e )
{
//string name = ddloutlet.SelectedValue.ToString ();
//cal
try
{
System.IO.FileInfo file = new System.IO.FileInfo(fileupload1.PostedFile.FileName);
string fname = file.Name.Remove((file.Name.Length - file.Extension.Length), file.Extension.Length);
fname = fname + DateTime.Now.ToString("_ddMMyyyy_HHmmss") + file.Extension;
fileupload1.PostedFile.SaveAs(Server.MapPath("locations/") + fname);
string filexetion = file.Extension;
if ( filexetion == ".xlsx" )
{
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + Server.MapPath ( "locations/" ) + fname + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
}
else if ( filexetion == ".xls" )
{
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath ( "locations/" ) + fname + ";" + "Extended Properties=\"Excel 8.0;HDR=Yes; \"";
}
OleDbConnection connection = new OleDbConnection(excelConnectionString);
OleDbCommand command = new OleDbCommand("Select * FROM [Sheet1$]", connection);
connection.Open();
OleDbDataReader dr = command.ExecuteReader();
SqlConnection conn = new SqlConnection(strconnection);
conn.Open();
try
{
if (dr.Read() == true)
{
while (dr.Read())
{
string locationname = dr["Location Name"].ToString();
string status = dr["Status"].ToString();
if (locationname != "" && status != "")
{
string query = " select locationname from tbllocations where locationname='" + locationname + "' and outletid='" + Session["outlet_id"].ToString() + "'";
// conn.Open();
SqlCommand cmdquery = new SqlCommand(query, conn);
SqlDataReader drreader;
drreader = cmdquery.ExecuteReader();
if (drreader.Read())
{
c = true;
ssss = ssss + locationname + ",";
// ss = ssss.Split(',');
}
else
{
drreader.Close();
string qryprduct = "insert into tbllocations(locationname,status,outletid,cityid)values('" + locationname + "','" + status + "','" + Session["outlet_id"].ToString() + "','" + Session["cityid"].ToString() + "')";
SqlCommand cmd1 = new SqlCommand(qryprduct, conn);
conn.Close();
conn.Open();
cmd1.ExecuteNonQuery();
lblerror1.Visible = true;
lblerror1.Text = "Locations uploaded Sucess";
//conn.Close();
}
drreader.Close();
}
}
// connection.Close (); conn.Close ();
}
else
{
lblerror1.Text = "There is a empty excel sheet file,plz check";
lblerror1.Visible = true;
}
}
catch (Exception ex)
{
lblerror1.Visible = true;
lblerror1.Text = "Plz check the excel file formate";
}
finally
{
connection.Close(); conn.Close();
bind();
if (c == true)
{
lblerror1.Visible = true;
lblerror1.Text = "In excel this loactions are already exist. Please check,";
//for (int i = 0; i < ss.Length; i++)
//{
lblerror3.Visible = true;
lblerror3.Text = ssss;
//}
}
}
}
catch
{
}
}
The above code uploading is working but in excel 1st record is not uploading ,please tell me the what is the problem and give me suggestion please.
excel data is
Location Name Status
test1 1
test2 1
test3 1
test4 0
test5 1
test6 0
test7 1
test8 0
test9 1
test10 1
Thanks
Pradeep

You need to remove the
if (dr.Read() == true)
because it is immediately followed by a
while (dr.Read())
Each of these will read a record and the first one will skip the first row of the file

Related

How to insert same id after insert update in c#

I'm trying to create an attendance project. I'm using update & insert in my code. Please check my code below. I know I'm vulnerable to SQL injection.
My problem is when I tried to Time In using the same ID even if I use that same ID for time out, it displays the time out not time-in. Any idea how I can time in again using same ID?
MySqlCommand cmd = new MySqlCommand("SELECT * FROM tbl_student_list INNER JOIN attendance_tbl On tbl_student_list.ID = attendance_tbl.stud_id WHERE stud_id ='" + dataGridView1.Rows[i].Cells["Column1"].Value + "'", conn);
cmd.Parameters.AddWithValue("stud_id", dataGridView1.Rows[i].Cells["Column1"].Value);
conn.Open();
MySqlDataReader DataRead = cmd.ExecuteReader();
DataRead.Read();
This is my Update Code:
//If already Time-In execute Time-Out
if (DataRead.HasRows)
{
dataGridView1.Rows[i].Cells["Column3"].Value = DataRead[1].ToString();
dataGridView1.Rows[i].Cells["Column4"].Value = DataRead[2].ToString();
dataGridView1.Rows[i].Cells["Column2"].Value = DateTime.Now.ToString("yy/MM/dd");
byte[] images = ((byte[])DataRead[3]);
if (images == null)
{
pictureBox1.Image = null;
}
else
{
MemoryStream mstreem = new MemoryStream(images);
pictureBox1.Image = Image.FromStream(mstreem);
conn.Close();
conn.Open();
string sqla = "Update attendance_tbl SET TimeOut = '" + Time + "' , Name ='" + dataGridView1.Rows[i].Cells["Column3"].Value + "' where stud_id = '" + dataGridView1.Rows[i].Cells["Column1"].Value + "'";
cmd = new MySqlCommand(sqla, conn);
cmd.ExecuteNonQuery();
dataGridView1.Rows[i].Cells["Column7"].Value = DateTime.Now.ToLongTimeString();
This is My Insert Code:
//IF Not In Execute Time-In/Not exist in tbl attendance
string sqlQu = "select ID,Name,Course,Image from tbl_student_list where ID= '" + dataGridView1.Rows[i].Cells["Column1"].Value + "'";
md = new MySqlCommand(sqlQu, conn);
MySqlDataReader DataReaders = cmd.ExecuteReader();
DataReaders.Read();
if (DataReaders.HasRows)
{
dataGridView1.Rows[i].Cells["Column3"].Value = DataReaders[1].ToString();
dataGridView1.Rows[i].Cells["Column4"].Value = DataReaders[2].ToString();
dataGridView1.Rows[i].Cells["Column2"].Value = DateTime.Now.ToString("yy/MM/dd");
byte[] images = ((byte[])DataReaders[3]);
if (images == null)
{
pictureBox1.Image = null;
}
else
{
MemoryStream mstreem = new MemoryStream(images);
pictureBox1.Image = Image.FromStream(mstreem);
Purpose f2 = new Purpose();
if (f2.ShowDialog() == DialogResult.OK)
{
dataGridView1.Rows[i].Cells["Column5"].Value = f2.Rad;
}
conn.Close();
conn.Open();
string sql = "insert into attendance_tbl(stud_id,Date,Name,Course,Purpose,TimeIn)values('" + dataGridView1.Rows[i].Cells["Column1"].Value + "','" + Date + "','" + dataGridView1.Rows[i].Cells["Column3"].Value + "','" + dataGridView1.Rows[i].Cells["Column4"].Value + "','" + dataGridView1.Rows[i].Cells["Column5"].Value + "','" + Time + "')";
cmd = new MySqlCommand(sql, conn);
cmd.ExecuteNonQuery();
dataGridView1.Rows[i].Cells["Column6"].Value = DateTime.Now.ToLongTimeString();

Importing DBF file in SQL Server 2012

I have over 200+ dbf files having different schema. I have used SSIS to import .dbf files, but in order to automate the task I want to use OpenRowset. OpenRowSet is working fine for Excel Files, but not for .dbf.
I have written
SELECT [LRSNum],[AppUpdD],[AppStat],[PIN] FROM OPENROWSET('MICROSOFT.ACE.OLEDB.12.0','dBASE 5.0;Database=D:\Sales- data\SalesSourcefile\2016\December\Shape\Martin\real_land\', 'SELECT [LRSNum],[AppUpdD],[AppStat],[PIN] FROM real_land.dbf');
Any help will be appreciated.
I am using SQL Server 2012, Windows 8.1.
Installed Foxpro driver, but when selected foxpro using DTS, it fails.
FYI - You can do automated uploads of DBFs to SQL Server using SQL Server Upsizing Wizard for FoxPro.
With this tool, you have to do the uploading from FoxPro, and the DBFs must be attached to a FoxPro DBC.
http://www.codemag.com/article/0703052
The latest version if available from the VFPx site.
Finally, this is working
SELECT * FROM OPENROWSET ('MICROSOFT.ACE.OLEDB.12.0','dBase 5.0;HDR=YES;IMEX=2;DATABASE=\Dbf Directory\',
'SELECT * FROM dbf_filename.dbf')
I once had to do this too and wrote some C# code for the import.
Just as a try: With this line I open the connection within C#
var con = new OdbcConnection("Driver={{Microsoft dBASE Driver (*.dbf)}};Dbq=C:\\SomePath;DriverID=277;");
Might be, that you can get something out of this.
Some C# code
The following code is taken from one of my C# projects. I modified it to be neutral, but I cannot guarantee, that this is working right so:
public List<string> Ambus;
public List<string> Tbls;
public List<string> errList;
public List<string> SQLs;
private void btnImport_Click(object sender, EventArgs e) {
SqlConnection sqlcon;
SqlCommand sqlcmd;
SQLs.Clear();
Tbls.Clear();
var con = new OdbcConnection("Driver={{Microsoft dBASE Driver (*.dbf)}};Dbq=C:\\SomePath;DriverID=277;");
con.Open();
var tbls = con.GetSchema(OdbcMetaDataCollectionNames.Tables);
foreach (System.Data.DataRow r in tbls.Rows) {
Tbls.Add(r["TABLE_NAME"].ToString());
}
DataTable cols = null;
var sb = new StringBuilder();
int i = 0;
foreach (var tblnm in Tbls) {
i++;
sb.Clear();
try {
cols = con.GetSchema(OdbcMetaDataCollectionNames.Columns, new string[] { null, null, tblnm, null });
sb.AppendFormat(" CREATE TABLE dbo.[{0}](TableName VARCHAR(100) NOT NULL ", tblnm);
int count = 0;
foreach (DataRow colrow in cols.Rows) {
var colInf = string.Format(" ,{0} {1} NULL", colrow["COLUMN_NAME"].ToString(), this.createDataType(colrow["TYPE_NAME"].ToString(), colrow["COLUMN_SIZE"].ToString(), colrow["DECIMAL_DIGITS"].ToString(), colrow["NUM_PREC_RADIX"].ToString()));
sb.Append(colInf);
count++;
}
sb.Append("); ");
SQLs.Add(sb.ToString());
sb.Clear();
var cmd = new OdbcCommand("SELECT * FROM [" + tblnm + "]", con);
var reader = cmd.ExecuteReader();
while (reader.Read()) {
var vals = createVals(cols, reader, tblnm);
string insStat = string.Format(" INSERT INTO dbo.[{0}] VALUES ('{0}',{1});", tblnm, vals);
SQLs.Add(insStat);
}
}
catch (Exception exo) {
errList.Add(string.Format("{0}:{1}", tblnm, exo.Message));
}
con.Close();
sqlcon = new SqlConnection("Data Source=SomeSQLServer;Initial Catalog=master;User ID=sa;pwd=SomePwd");
sqlcon.Open();
sqlcmd = new SqlCommand("USE SomeTargetDB;", sqlcon);
sqlcmd.ExecuteNonQuery();
i = 0;
foreach (string s in SQLs) {
i++;
//Progress-output: this.Text = string.Format("{0} von {1}", i, SQLs.Count);
sqlcmd = new SqlCommand(s, sqlcon);
sqlcmd.ExecuteNonQuery();
}
sqlcon.Close();
}
}
private string createDataType(string typ, string size, string dec, string prec) {
switch (typ.ToLower()) {
case "char":
return "NVARCHAR(" + size + ")";
case "logical":
return "BIT";
case "numeric":
dec = dec == string.Empty ? null : dec;
prec = prec == string.Empty ? null : prec;
int d = int.Parse(dec ?? "0");
int p = int.Parse(prec ?? "0");
if (d == 0 && p == 0)
return "INT";
else if (d > 0 && p > 0)
return string.Format("DECIMAL({0},{1})", d, p);
else if (d == 0 && p > 0)
return "FLOAT";
else
return null;
case "date":
return "DATETIME";
default:
return null;
}
}
private string createVals(DataTable cols, OdbcDataReader reader, string tblnm) {
var sb = new StringBuilder();
sb.Append("'" + tblnm + "'");
foreach (DataRow colrow in cols.Rows) {
var val = string.Empty;
try {
val = reader[colrow["COLUMN_NAME"].ToString()].ToString();
}
catch { }
if (val.Trim().Length == 0)
val = "NULL";
else {
if (colrow["TYPE_NAME"].ToString().ToLower() == "char")
val = val.Replace("'", "''");
if (colrow["TYPE_NAME"].ToString().ToLower() == "numeric")
val = val.Replace(".", "").Replace(",", ".");
if (colrow["TYPE_NAME"].ToString().ToLower() == "date") {
var d = DateTime.Parse(val, System.Globalization.CultureInfo.CurrentCulture);
if (d.Year < 1900 || d.Year > 2020)
d = new DateTime(1900, d.Month, d.Day, d.Hour, d.Minute, d.Second);
val = d.ToString("dd.MM.yyyy HH:mm:ss");
}
val = "'" + val + "'";
}
sb.AppendFormat(",{0}", val);
}
return sb.ToString();
}

'DATE' cannot hold values of type 'INTEGER'

I've set up an SQL database and used 'Date' as my column header which obviously has its own format as opposed to integer or char etc. However when I put in a date such as 2/11/2016 it gives me the error message - 'DATE' cannot hold values of type 'INTEGER'. Does anyone know what code I should be using? Here's my jsp below. All goes into DB when I remove all reference to date.
<%
int tableNum = 0;
String firstName = null;
String lastName = null;
String Address = null;
int Phone = 0;
java.sql.Date date = null;
int People = 0;
if (request.getParameter("table_num")!=null){
tableNum = Integer.parseInt(request.getParameter("table_num"));
}
if (request.getParameter("first")!=null){
firstName = request.getParameter("first");
}
if (request.getParameter("last")!=null){
lastName = request.getParameter("last");
}
if (request.getParameter("address")!=null){
Address = request.getParameter("address");
}
if (request.getParameter("phone")!=null){
Phone = Integer.parseInt(request.getParameter("phone"));
}
if (request.getParameter("date")!=null){
java.util.Date utilDate = new java.util.Date(request.getParameter("date"));
date = new java.sql.Date(utilDate.getTime());
}
if (request.getParameter("people")!=null){
People = Integer.parseInt(request.getParameter("people"));
}
if(tableNum != 0 && firstName != null && lastName != null && Address != null && Phone != 0 && date != null && People != 0){
String URL = "jdbc:derby://localhost:1527/Reservations";
String USERNAME= "johnpaul";
String PASSWORD= "purlease";
Connection myCon = null;
Statement ste = null;
PreparedStatement preparedStmt = null;
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
System.out.println("Connecting to DB...");
Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/Reservations","johnpaul", "purlease");
System.out.println("Connected successfuly");
System.out.println("Inserting records into table");
Statement st = con.createStatement();
String query = "INSERT INTO CUSTOMER_RESERVATIONS(TABLE_NUM,FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE,DATE,NUMBER_IN_PARTY)VALUES(" + tableNum + "," + "'" + firstName + "'" + "," + "'" + lastName + "'" + "," + "'" + Address + "'" + "," + Phone + "," + date + "," + People +")";
st.executeUpdate (query);
System.out.println("Records inserted");
}catch(SQLException se){
se.printStackTrace();
}catch(ClassNotFoundException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
}
%>

How can update contact in existing contact update to postal address

This is my code to existing contact to change the postal address code
ops = new ArrayList<ContentProviderOperation>();
rawContactID = ops.size();
///Insert code are working/////
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,rawContactID)
.withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET,addr)
.withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, edtcity.getText().toString())
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, edtpostcode.getText().toString())
enter code here
`enter code here` .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, edtcountry.getText().toString()).build());
//// I am trying this update record code but not working///
btn_upcontacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withSelection(String.valueOf(CONTENT_URI), new String[]{CommonDataKinds.StructuredPostal.RAW_CONTACT_ID + " = " + rawContactID})
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, addr)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withSelection(String.valueOf(CONTENT_URI), new String[]{CommonDataKinds.StructuredPostal.RAW_CONTACT_ID + " = " + rawContactID})
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, scity)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withSelection(String.valueOf(CONTENT_URI), new String[]{CommonDataKinds.StructuredPostal.RAW_CONTACT_ID + " = " + rawContactID})
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, scode)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withSelection(String.valueOf(CONTENT_URI), new String[]{CommonDataKinds.StructuredPostal.RAW_CONTACT_ID + " = " + rawContactID})
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,scountry)
.build());
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
I am update the record coding to btn_upcontacts listner but not working,Please Help me
I am trying the many code use are but not working
I have a simply edit the text andd update to the exsiting contact the postal address without the sqllite datbase
Advance in Thanks
int _contact_id = 10110; // your Conatct id
Uri rawContactUri = null;
Cursor rawContactCursor = null;
try {
// if some fields not available use rawContactUri as ID
rawContactUri = null;
rawContactCursor = context.getContentResolver().query(
ContactsContract.RawContacts.CONTENT_URI,
new String[]{ContactsContract.RawContacts._ID},
ContactsContract.RawContacts.CONTACT_ID + " = " + _contact_id,
null,
null);
if (!rawContactCursor.isAfterLast()) {
rawContactCursor.moveToFirst();
rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendPath("" + rawContactCursor.getLong(0)).build();
}
rawContactCursor.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rawContactCursor != null) {
rawContactCursor.close();
}
}
Boolean noAddress = true;
Cursor currAddr = null;
try {
Uri URI_ADDRESS = ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI;
String SELECTION_ADDRESS = ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.StructuredPostal.MIMETYPE + " = ?";
String[] SELECTION_ARRAY_ADDRESS = new String[]{
String.valueOf(_contact_id),
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
currAddr = context.getContentResolver().query(URI_ADDRESS, null, SELECTION_ADDRESS, SELECTION_ARRAY_ADDRESS, null);
if (currAddr.getCount() > 0) {
currAddr.moveToFirst();
while (!currAddr.isAfterLast()) {
noAddress = false;
currAddr.moveToNext();
}
} else {
noAddress = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (currAddr != null) {
currAddr.close();
}
}
if (noAddress) {
// address is not available
try {
String street_name = "strt";
String number ="num";
String apartment = "app";
String postal_code = "7777";
String state ="state";
String city = "cityty";
String country = "countrrry";
ContentValues adrsValues = new ContentValues();
adrsValues.put(ContactsContract.Data.RAW_CONTACT_ID, ContentUris.parseId(rawContactUri));
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, "1");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
(street_name.length() > 0 || number.length() > 0) ? number + " " + street_name : number + " " + street_name);
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD,
(apartment.length() > 0) ? apartment : "");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
(city.length() > 0) ? city : "");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
(state.length() > 0) ? state : "");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
(postal_code.length() > 0) ? postal_code : "");
adrsValues.put(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
(country.length() > 0) ? country : "");
adrsValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, adrsValues);
} catch (Exception e) {
isError = true;
e.printStackTrace();
}
} else {
// address is already available
try {
String street_name = "strt";
String number ="num";
String apartment = "app";
String postal_code = "7777";
String state ="state";
String city = "cityty";
String country = "countrrry";
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where1, AryStructuredAdd1)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
(street_name.length() > 0 || number.length() > 0) ? number + " " + street_name : number + " " + street_name)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD,
(apartment.length() > 0) ? apartment : "")
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
(city.length() > 0) ? city : "")
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
(state.length() > 0) ? state : "")
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
(postal_code.length() > 0) ? postal_code : "")
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
(country.length() > 0) ? country : "")
.build());
} catch (Exception e) {
isError = true;
e.printStackTrace();
}
}

Select results truncated without error message

I'm using Google Cloud SQL from an App Engine application via Java and JDBC.
I select rows of a table using following code:
public void processGcmRegistrations(String whereCondition, String appName,
String[] appVariants, boolean onlyTestDevices,
String orderByCondition,
GcmRegistrationProcessor processor) throws DbException {
if (whereCondition == null && appName == null)
throw new IllegalArgumentException("One of the parameters \"whereCondition\", " +
"\"appNmae\" must not be null.");
if (whereCondition == null) {
whereCondition = "APP_NAME = '" + appName + "' " +
createInListCondition("APP_VARIANT", appVariants);
if (onlyTestDevices)
whereCondition += " AND TEST_DEVICE = 1 ";
}
String orderByConditionStr = "";
if (orderByCondition != null)
orderByConditionStr = " ORDER BY " + orderByCondition;
String selectStmt = "SELECT GCM_ID, GCM_REGISTRATION_TIME, APP_NAME, APP_VARIANT, " +
"INSTALLATION_ID, DEVICE, LAST_UPDATE " +
"FROM GcmRegistration WHERE " + whereCondition + orderByConditionStr;
log.info("GcmIds Select: " + selectStmt);
ResultSet rs = null;
try {
long start = System.currentTimeMillis();
rs = dbConnection.createStatement().executeQuery(selectStmt);
log.info("Select duration: " + ((System.currentTimeMillis()-start)/1000) + " secs.");
int count = 0;
while (rs.next()) {
GcmRegistration reg = new GcmRegistration();
reg.gcmId = rs.getString(1);
reg.gcmRegistrationTime = rs.getLong(2);
reg.appName = rs.getString(3);
reg.appVariant = rs.getString(4);
reg.installationId = rs.getString(5);
reg.device = rs.getString(6);
reg.lastUpdate = rs.getLong(7);
processor.processGcmRegistration(reg);
count++;
}
log.info(count + " GcmRegistrations processed.");
} catch (Exception e) {
String errorMsg = "Selecting GCM_IDs from table GcmRegistration failed.";
log.log(Level.SEVERE, errorMsg, e);
throw new DbException(errorMsg, e);
} finally {
if (rs != null)
rs.close();
}
}
I always execute this method with the same parameters and receive usually about 152000 rows.
In rare cases (I guess 1 from 50) I receive only about 62000 rows without any exception! rs.next() returns false, although not all result rows are delivered.
For Google: Last time this happened was 8/22/14 23:20 (MEST)