Insert multiple rows into SQL Server Java Android - android
Im Beginner Android Developer.I need some help
I want to insert multiple rows into a SQL Server table at once using Java in Adnroid.
i have 2 table TransH, and TransD. for TransH I have successfully saved, but TransD is getting data from multiple item listview i stuck to insert in table.
EntryHD.java source
btnsave.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
String pono = po.getText().toString();
String supppo = kdsupp.getText().toString();
String kdcabang = pohkdcabang.getText().toString();
String gross = pohgross.getText().toString();
String ppn = pohppn.getText().toString();
String qty = pohqty.getText().toString();
String nofakpo = nofak.getText().toString();
String kdjt = kodejt.getText().toString();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance(); System.out.println(dateFormat.format(cal.getTime()));
DateFormat dateFormatPDT = new SimpleDateFormat("yyyyMMdd-HH:mm:ss");
Calendar calpdt = Calendar.getInstance(); System.out.println(dateFormat.format(calpdt.getTime()));
connect = CONN();
try { if (connect != null) {
String query = "insert into tbTr_BoTrans_H (BOH_RECORDID,BOH_KODECABANG,BOH_NODOC,BOH_TGLDOC," +
"BOH_TIPEDOC,BOH_KODELOK,BOH_TIPESTOCK,BOH_TIPESTOCK2,BOH_NOFAKTUR,BOH_TGLFAKTUR,BOH_NOREFF," +
"BOH_TGLREFF,BOH_ITEM,BOH_QTY,BOH_GROSS,BOH_PPN,BOH_PPNBM,BOH_BONUS1,BOH_BONUS2,BOH_DISC1," +
"BOH_DISC2,BOH_PEMBULATAN,BOH_KODESUP,BOH_KODEGUDANG,BOH_KODEGUDANG2,BOH_IDRKODE,BOH_KODEJT," +
"BOH_KODESALES,BOH_SALESKOMISI,BOH_KETERANGAN,BOH_BYRTOKO,BOH_IDTRANS) values ('','"+kdcabang+"',''," +
"'"+dateFormat.format(cal.getTime())+"',1,'01','01','','"+nofakpo+"'," +
"'"+dateFormat.format(cal.getTime())+"','"+pono+"'," +
"'"+dateFormat.format(cal.getTime())+"',1,'"+qty+"'," +
"'"+gross+"','"+ppn+"',0,0,0,0,0,0,'"+supppo+"','"+kdcabang+"'," +
"'"+kdcabang+"','IDR','"+kdjt+"','',0,'','','"+dateFormatPDT.format(calpdt.getTime())+"-PDT')"; PreparedStatement preparedStatement = connect.prepareStatement(query); preparedStatement.executeUpdate();
List<HashMap<String, String>> data = dbController.getAllDBPO();
if (data.size() != 0) {
SimpleAdapter adapter = new SimpleAdapter( POReceivingActivity.this, data, R.layout.lst_poreceiving, new String[]{"po_barcode", "po_product", "po_uom", "po_price", "po_qtyhasil"}, new int[]{ R.id.lblbarcode, R.id.lblproduct, R.id.lbluom, R.id.lblprice, R.id.lblqty}); lstpo.setAdapter(adapter);
}
String sql = "insert into tbTr_BoTrans_D (BOD_KODECABANG,BOD_NODOC,BOD_NOURUT,BOD_PRDCD,BOD_QTY," +
"BOD_HRGSAT,BOD_GROSS,BOD_PPN,BOD_PPNBM,BOD_BONUS1,BOD_BONUS2,BOD_DISC1,BOD_DISCRPH1," +
"BOD_DISC2,BOD_DISCRPH2,BOD_BERAT,BOD_HRGGRAM," +
"BOD_KODEPBR,BOD_IDTRANS) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; PreparedStatement preparedStatement1 = connect.prepareStatement(sql); for (int i = 0; i < data.size(); i++) {
preparedStatement1.setString(1, data.get(0).toString()); preparedStatement1.addBatch();
} preparedStatement1.executeBatch();
I hope it can insert multiple rows in table TransD .
with the data listview and any other value is null
BOD_PRDCD BOD_HRGSAT BOD_QTY
123 1200 5
122 2000 10
List<HashMap<String, String>> data = dbController.getAllDBPO(); if (data.size() != 0) { SimpleAdapter adapter = new SimpleAdapter( POReceivingActivity.this, data, R.layout.lst_poreceiving, new String[]{"po_barcode", "po_product", "po_uom", "po_price", "po_qtyhasil"}, new int[]{ R.id.lblbarcode, R.id.lblproduct, R.id.lbluom, R.id.lblprice, R.id.lblqty}); lstpo.setAdapter(adapter);
}
String sql = "insert into tbTr_BoTrans_D (BOD_KODECABANG,BOD_NODOC,BOD_NOURUT,BOD_PRDCD,BOD_QTY," +
"BOD_HRGSAT,BOD_GROSS,BOD_PPN,BOD_PPNBM,BOD_BONUS1,BOD_BONUS2,BOD_DISC1,BOD_DISCRPH1," +
"BOD_DISC2,BOD_DISCRPH2,BOD_BERAT,BOD_HRGGRAM," +
"BOD_KODEPBR,BOD_IDTRANS) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; PreparedStatement preparedStatement1 = connect.prepareStatement(sql); for (int i = 0; i < data.size(); i++) {
preparedStatement1.setString(1, data.get(0).toString()); preparedStatement1.addBatch();
} preparedStatement1.executeBatch();
Related
Android SQLiteStatement Insert, nothing happen
i have some data from SoapObject, i want insert to sqlite, for better performance, i use the following code : public void testInsert(String sql, SoapObject rs, int index) { try { sql = "INSERT INTO NSPMasterHarga (KdBarang, Wilayah, HargaJual1, HargaJual2) VALUES (?, ?, ?, ?)"; theDatabase = getWritableDatabase(); theDatabase.beginTransaction(); String drop = "DROP TABLE IF EXISTS NSPMasterHarga"; SQLiteStatement stmtDrop = theDatabase.compileStatement(drop); stmtDrop.execute(); String create = "CREATE TABLE NSPMasterHarga (KdBarang TEXT PRIMARY KEY, Wilayah TEXT, HargaJual1 TEXT, HargaJual2 TEXT)"; SQLiteStatement stmtCreate = theDatabase.compileStatement(create); stmtCreate.execute(); SQLiteStatement stmt = theDatabase.compileStatement(sql); int count = rs.getPropertyCount(); for (int i = 0; i < count; i++) { SoapObject row = (SoapObject) rs.getProperty(i); for (int j = 1; j <= index; j++) { stmt.bindString(j, row.getProperty(j - 1).toString().replace("anyType{}", "")); } long entryID = stmt.executeInsert(); stmt.clearBindings(); } /*for (int i = 0; i < NUMBER_OF_ROWS; i++) { //generate some values stmt.bindString(1, randomName); stmt.bindString(2, randomDescription); stmt.bindDouble(3, randomPrice); stmt.bindLong(4, randomNumber); long entryID = stmt.executeInsert(); stmt.clearBindings(); }*/ theDatabase.setTransactionSuccessful(); theDatabase.endTransaction(); theDatabase.close(); } catch (Exception ex) { String err = ex.getMessage(); } } When debug, i've got nothing error, but the data not insert to my sqlite. Any idea or clue ? Thanks
for better performance I'm not so sure which part of the code you are referring to. Opening and closing the database after each interaction is terrible for performance. The SQLiteOpenHelper takes care of all this, so you don't need to do anything manually. Try the following alternative to insert an entry: public boolean addEntry(){ db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("column1", "value1"); // make sure the type corresponds to your sql column type values.put("column2", "value2"); values.put("column3", "value3"); values.put("column4Int", 1); long newRowId = db.insert(TABLE_NAME, null, values); Log.d("DBHelper", "Added row " + newRowId + " to DB."); return newRowId != -1; // -1 means it failed }
Multiple insert SQLite : data can't save
i am trying to insert multiple data into sqlite, i get data from server in json format, i parse the data from my activity. and trying to save into my database. But i wonder, how can i save data in sqlite multiple times? I get some references and and check in my logcat everything is alright. How can I solve this? Thanks in advance public List<ModelAgen> updateTaccessUser(){ List<ModelAgen> data = new ArrayList<ModelAgen>(); SQLiteDatabase db = this.getWritableDatabase(); db.beginTransaction(); try { String update = "INSERT INTO taccesagen(" + "id," + "ref_magen," + "ref_tuser," + "def," + "nama" + ")" + " VALUES" + "(?, ?, ?, ?, ?)"; for (int i = 0; i < data.size(); i++) { String kondisi; if (data.get(i).getDef() == "t") { kondisi = "1"; } else { kondisi = "0"; } SQLiteStatement insert = db.compileStatement(update); insert.bindLong(1, data.get(i).getId()); insert.bindString(2, data.get(i).getRef_magen()); insert.bindString(3, data.get(i).getRef_tuser()); insert.bindString(4, kondisi); insert.bindString(5, data.get(i).getNama()); insert.execute(); } db.setTransactionSuccessful(); }finally { db.endTransaction(); } return data; }
You can insert multiple records like this way try { for(int i=0;i<lstModelAgen.size();i++) { ContentValues contentValues = new ContentValues(); contentValues.put("column1", lstModelAgen.get(i).getcolumn1Value); contentValues.put("column2", lstModelAgen.get(i).getcolumn2Value()); db.insert("taccesagen", null, contentValues); } } catch (Exception e) { e.printStackTrace(); }
Try below for (int i = 0; i < data.size(); i++) { String kondisi; if (data.get(i).getDef() == "t") { kondisi = "1"; } else { kondisi = "0"; } ArrayList<ContentValues> arrvals = new ArrayList<ContentValues>(); ContentValues values = new ContentValues(); values.put("id", data.get(i).getId()); values.put("ref_magen", data.get(i).getRef_magen()); values.put("ref_tuser",data.get(i).getRef_tuser() ); values.put("def", kondisi); values.put("nama", data.get(i).getNama()); arrvals.add(values); } db.InsertData("taccesagen", arrvals);
Insert JSON to SQLite table on Android
i have a JSONObject : {"Table1":[{"row1":"1","B":"2"},{"row2":"1","B1":"2"}],"Table2":[{"C":"1","D":"1145"},{"C":"1","D":"1145"}],"Table3":[{"E":"62","F":"1"},{"C":"1","D":"1145"}]} how can I insert into sqlite foreach table ? now use this code: for (Iterator<String> iterator = mJson.keys(); iterator.hasNext(); ) { String tableName = iterator.next(); if (mJson.optJSONArray(tableName) != null) { resetTable(tableName); JSONArray tableArray = mJson.optJSONArray(tableName); for (int i = 0; i < tableArray.length(); i++) { JSONObject tableData = tableArray.getJSONObject(i); ContentValues Values = new ContentValues(); for (Iterator<String> iter = tableData.keys(); iter.hasNext(); ) { String key = iter.next(); Values.put(key, tableData.get(key).toString()); } db.insert(tableName, null, Values); } } } but i want fastest and better way
Use bulk insert: for (Iterator<String> iterator = mJson.keys(); iterator.hasNext(); ) { String tableName = iterator.next(); if (mJson.optJSONArray(tableName) != null) { resetTable(tableName); String sql = "INSERT INTO " + tableName + " VALUES (?);"; SQLiteStatement statement = db.compileStatement(sql); db.beginTransaction(); JSONArray tableArray = mJson.optJSONArray(tableName); for (int i = 0; i < tableArray.length(); i++) { JSONObject tableData = tableArray.getJSONObject(i); for (Iterator<String> iter = tableData.keys(); iter.hasNext(); ) { String key = iter.next(); statement.clearBindings(); statement.bindString(1,tableData.get(key).toString()); statement.execute(); } } db.setTransactionSuccessful(); db.endTransaction(); } }
You can use ContentValues with beginTransaction into SQLite that is quite easy as well as faster then prepared statements For this you have to create ContentValues Array previously or create Content values object into your loop. and pass into insert method .this solution solve your both of problem in one. mDatabase.beginTransaction(); try { for (ContentValues cv : values) { long rowID = mDatabase.insert(table, " ", cv); if (rowID <= 0) { throw new SQLException("Failed to insert row into "); } } mDatabase.setTransactionSuccessful(); count = values.length; } finally { mDatabase.endTransaction(); } You can only pass Content Values Object like for loop and insert and in above code Transaction are used so it will speed up data base storage .
sqlite register is updated with wrong values on android app
In my current android project, the method for update a row in my sqlite database receive as parameter a array like this: String form[] = {id, first_name, last_name, email, login, password}; user.update(form); which is processed through this code: public void update(String[] data) { try { Model object = clazz.newInstance(); List<String> campos = object.getFields(); List<String> pares = new ArrayList<String>(); for(int i=1; i<campos.size(); i++) pares.add(campos.get(i)+" = ?"); String spares = pares.toString().replace("[", "").replace("]", "").replace(",", " and "); String UPDATE = "update " + clazz.getSimpleName() + " set " + spares + " where _id='" + data[0] + "'"; SQLiteDatabase db = openHelper.getWritableDatabase(); SQLiteStatement updateStmt = db.compileStatement(UPDATE); for(int i=1; i<data.length; i++) updateStmt.bindString(i, data[i]); updateStmt.executeUpdateDelete(); } catch (Exception e) { e.printStackTrace(); } } generating a sql instruction like that: update Usuario set first_name = ? and last_name = ? and email = ? and login = ? and password = ? where _id='1' the problem is only the first column is being updated, and with the value '0'. Anyone can se what's wrong here?
The syntax for an SQL UPDATE is like update Usuario set first_name = ?, last_name = ? ... i.e. commas intead of AND. The AND makes it a boolean expression that evaluates to 0 (false).
Android copy values from table and insert in another
I'm trying to copy all the data in a database table, which correspond to the WHERE clause, and insert them into another table. I'm trying this code, but in the table prev there are only 2 records in the table Ver are inserted more than 100 records .... why? private void Tras() { String numero_ricevuto = (i.getStringExtra("numero")); SQLiteDatabase db = mHelper.getWritableDatabase(); String sql = "SELECT data, unita_di_misura FROM prev WHERE numero ='"+numero_ricevuto+"'"; Cursor c = db.rawQuery(sql, null); int count = c.getCount(); String[] data = new String[count]; String[] unita_di_misura = new String[count]; for(int i=0; i<count; i++) { c.moveToNext(); data[i] = c.getString(0); unita_di_misura[i] = c.getString(1); } for(int i=0 ;i < data.length;i++){ ContentValues cv = new ContentValues(); cv.put(VerTable.SI_NO, "0"); cv.put(VerTable .DATA, data[i]); cv.put(VerTable .U_M, e.unita_di_misura[i]); db.insert(VerTable .TABLE_NAME, null, cv); } c.close(); db.close(); }
Try this 3 line solution hope this will help you private void Tras() { String numero_ricevuto = (i.getStringExtra("numero")); SQLiteDatabase db = mHelper.getWritableDatabase(); String sql = "INSERT INTO "+VerTable .TABLE_NAME+" SELECT 0,data, unita_di_misura FROM prev WHERE numero = '"+numero_ricevuto+"'"; db.execSQL(sql); db.close(); }
but in the table prev there are only 2 records in the table Ver are inserted more than 100 records .... why? Possibly you ran the code more than once. Also, pulling data from db only to insert it back is not very efficient. It's better to let the database engine do the work for you, e.g. db.execSQL("INSERT INTO " + VerTable.TABLE_NAME + "(" + VerTable.SI_NO + "," VerTable.DATA + "," + VerTable.U_M + ") " + "SELECT 0, data, unita_di_misura FROM prev WHERE numero=?", new String[] { numero_ricevuto }); Using ? params also avoids the possiblity of string SQL injection.