I have worked newly in a app which uses Sqlite Db to retreive and save datas. I have finished the entire project. My app works perfectly for first log in. When i log in using different user id, it throws sqlite constraint exception. My Db field remains the same where as i have used userid as unique element to fetch values for the user.
How to overcome this exception? Else i need to change entire table structure?
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + Table_variables + "(id INTEGER PRIMARY KEY ,var1 text, var2 text, var3 text, var4 text, var5 text, var6 text, var7 text, var8 text, var9 text, var10 text, userid text )");
db.execSQL("CREATE TABLE " + Table_values + "(id INTEGER PRIMARY KEY , val1 text, val2 text, val3 text, val4 text, val5 text, val6 text, val7 text, val8 text, val9 text, val10 text ,userid text )");
db.execSQL("CREATE TABLE " + Table_ListId + "(id INTEGER PRIMARY KEY , val1 text, val2 text, val3 text, val4 text, val5 text, val6 text, val7 text, val8 text, val9 text, val10 text,userid text )");
db.execSQL("CREATE TABLE " + Table_PaymentOptions + "(id INTEGER PRIMARY KEY, var1 text, var2 text, var3 text, var4 text, var5 text, var6 text, var7 text, var8 text , userid text, randomID text)");
db.execSQL("CREATE TABLE " + Table_PaymentRemider + "(id INTEGER PRIMARY KEY, plc text, agencyname text,amountDue text, datedue text, reminderNotes text, reminderDate text, reminderTime text, toggleOption text, userid text, uniqueID text)");
}
// TODO TO INSERT REGION DATA
public boolean insertData(Context context, ArrayList list, ArrayList list1, ArrayList list2, String plcData, String agencyName, String userid) {
SQLiteDatabase myDB = getWritableDatabase("my_paygov_secure_key");
System.out.println("AGENCY_NAME_in DBHANDLER" + agencyName);
if (list.size() == 0) {
} else {
for (int i = 0; i < list.size(); i++) {
System.out.println("LIST-label and List-Edittext" + list.get(i));
}
boolean dbCheck = CheckIsDataAlreadyInDBorNot(Table_variables, "id", plcData, "userid", userid);
if (dbCheck) {
String query = "UPDATE " + Table_variables + " SET var2='" + list.get(0) + "',var3='" + list.get(1) + "',var4='" + list.get(2) + "',var5='" + list.get(3) + "',var6='" + list.get(4) + "',var7='" + list.get(5) + "',var8='" + list.get(6) + "',var9='" + list.get(7) + "',var10='" + list.get(8) + "' WHERE id =' " + plcData + " ' and userid='" + userid + "'";
String query1 = "UPDATE " + Table_values + " SET val2='" + list1.get(0) + "',val3='" + list1.get(1) + "',val4='" + list1.get(2) + "',val5='" + list1.get(3) + "',val6='" + list1.get(4) + "',val7='" + list1.get(5) + "',val8='" + list1.get(6) + "',val9='" + list1.get(7) + "',val10='" + list1.get(8) + "' WHERE id =' " + plcData + " ' and userid='" + userid + "'";
String query2 = "UPDATE " + Table_ListId + " SET val2='" + list2.get(0) + "',val3='" + list2.get(1) + "',val4='" + list2.get(2) + "',val5='" + list2.get(3) + "',val6='" + list2.get(4) + "',val7='" + list2.get(5) + "',val8='" + list2.get(6) + "',val9='" + list2.get(7) + "',val10='" + list2.get(8) + "' WHERE id =' " + plcData + " ' and userid='" + userid + "'";
myDB.execSQL(query);
myDB.execSQL(query1);
myDB.execSQL(query2);
} else {
String query = "INSERT INTO " + Table_variables + " VALUES('" + plcData + "', '" + agencyName + "','" + list.get(0) + "','" + list.get(1) + "','" + list.get(2) + "','" + list.get(3) + "','" + list.get(4) + "','" + list.get(5) + "','" + list.get(6) + "','" + list.get(7) + "','" + list.get(8) + "','" + userid + "');";
String query1 = "INSERT INTO " + Table_values + " VALUES('" + plcData + "','" + agencyName + "','" + list1.get(0) + "','" + list1.get(1) + "','" + list1.get(2) + "','" + list1.get(3) + "','" + list1.get(4) + "','" + list1.get(5) + "','" + list1.get(6) + "','" + list1.get(7) + "','" + list1.get(8) + "','" + userid + "');";
String query2 = "INSERT INTO " + Table_ListId + " VALUES('" + plcData + "','" + agencyName + "','" + list2.get(0) + "','" + list2.get(1) + "','" + list2.get(2) + "','" + list2.get(3) + "','" + list2.get(4) + "','" + list2.get(5) + "','" + list2.get(6) + "','" + list2.get(7) + "','" + list2.get(8) + "','" + userid + "');";
myDB.execSQL(query);
myDB.execSQL(query1);
myDB.execSQL(query2);
}
return true;
}
return false;
}
// TODO TO INSERT CARD DETAILS
public boolean insertCardDetails(Context context, ArrayList list, String cardNumber, String userid, String randomID) {
SQLiteDatabase myDB = getWritableDatabase("my_paygov_secure_key");
// Integer i = Integer.parseInt(cardNumber);
long card = Long.valueOf(cardNumber).longValue();
int ccnumber = (int) card;
/* for (int i = 0; i < list.size(); i++) {
System.out.println("LIST VALUE" + i + list.get(i).toString());
}*/
boolean dbCheck = CheckIsDataAlreadyInDBorNot(Table_PaymentOptions, "randomID", randomID, "userid", userid);
if (dbCheck) {
String query = "UPDATE " + Table_PaymentOptions + " SET var1='" + list.get(0) + "',var2='" + list.get(1) + "',var3='" + list.get(2) + "',var4='" + list.get(3) + "',var5='" + list.get(4) + "',var6='" + list.get(5) + "',var7='" + list.get(6) + "',var8='" + list.get(7) + "' WHERE randomID ='" + randomID + "' and userid='" + userid + "'";
} else {
String query = "INSERT INTO " + Table_PaymentOptions + " VALUES('" + ccnumber + "', '" + list.get(0) + "','" + list.get(1) + "','" + list.get(2) + "','" + list.get(3) + "','" + list.get(4) + "','" + list.get(5) + "','" + list.get(6) + "','" + list.get(7) + "','" + userid + "', '" + randomID + "');";
myDB.execSQL(query);
}
return false;
}
// TO INSERT DATA FOR REMINDER
public boolean myPaymentReminder(Context context, ArrayList list, int plcData, String userid) {
SQLiteDatabase myDB = getWritableDatabase("my_paygov_secure_key");
boolean dbCheck = CheckIsDataAlreadyInDBorNot(Table_PaymentRemider, "id", String.valueOf(plcData), "userid", userid);
if (dbCheck) {
String query = "UPDATE " + Table_PaymentRemider + " SET agencyname='" + list.get(1) + "',amountDue='" + list.get(2) + "',dateDue='" + list.get(3) + "',reminderNotes='" + list.get(4) + "',reminderDate='" + list.get(5) + "',reminderTime='" + list.get(6) + "',toggleOption='" + list.get(7) + "', uniqueID='" + list.get(8) + "' WHERE id ='" + plcData + "' and userid = '" + userid + "'";
myDB.execSQL(query);
} else {
String query = "INSERT INTO " + Table_PaymentRemider + " VALUES('" + plcData + "', '" + list.get(0) + "','" + list.get(1) + "','" + list.get(2) + "','" + list.get(3) + "','" + list.get(4) + "','" + list.get(5) + "','" + list.get(6) + "','" + list.get(7) + "','" + userid + "','" + list.get(8) + "');";
myDB.execSQL(query);
}
System.out.println("PlcData" + plcData);
return true;
}
// TODO TO CHECK TABLE IS ALREADY PRESENT OR NOT
public boolean CheckIsDataAlreadyInDBorNot(String TableName,
String dbfield, String fieldValue, String dbfield1, String field1) {
SQLiteDatabase myDB = getWritableDatabase("my_paygov_secure_key");
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue + " and " + dbfield1 + " = '" + field1 + "'";
System.out.println("Check User id DB" + Query);
Cursor cursor = myDB.rawQuery(Query, null);
if (cursor.getCount() <= 0) {
cursor.close();
return false;
}
cursor.close();
return true;
}
THE EXCEPTION THAT I GET IN LOGCAT !
net.sqlcipher.database.SQLiteConstraintException: UNIQUE constraint failed: PLC_DETAILS_TABLE_VARIABLES.id: INSERT INTO PLC_DETAILS_TABLE_VARIABLES VALUES('36400', 'Indiana-Dearborn County-Environmental Health','Name','Dearborn Enviro','','','','','','','','1e2332d3-cc60-48eb-bca0-8499097411bc');
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + Table_variables + "(id INTEGER PRIMARY KEY ,var1 text, var2 text, var3 text, var4 text, var5 text, var6 text, var7 text, var8 text, var9 text, var10 text, userid text )");
db.execSQL("CREATE TABLE " + Table_values + "(id INTEGER PRIMARY KEY , val1 text, val2 text, val3 text, val4 text, val5 text, val6 text, val7 text, val8 text, val9 text, val10 text ,userid text )");
db.execSQL("CREATE TABLE " + Table_ListId + "(id INTEGER PRIMARY KEY , val1 text, val2 text, val3 text, val4 text, val5 text, val6 text, val7 text, val8 text, val9 text, val10 text,userid text )");
db.execSQL("CREATE TABLE " + Table_PaymentOptions + "(id INTEGER PRIMARY KEY, var1 text, var2 text, var3 text, var4 text, var5 text, var6 text, var7 text, var8 text , userid text, randomID text)");
db.execSQL("CREATE TABLE " + Table_PaymentRemider + "(id INTEGER PRIMARY KEY, plc text, agencyname text,amountDue text, datedue text, reminderNotes text, reminderDate text, reminderTime text, toggleOption text, userid text, uniqueID text)");
}
You have id as primary key. You get the unique constraint error when you insert a duplicate value in the table. Implement a method to check for duplicate IDs or surround execSQL("INSERT ...") with a try-catch block, either should work. The second way:
String query = "INSERT INTO " + Table_variables + " VALUES('" + plcData + "', '" + agencyName + "','" + list.get(0) + "','" + list.get(1) + "','" + list.get(2) + "','" + list.get(3) + "','" + list.get(4) + "','" + list.get(5) + "','" + list.get(6) + "','" + list.get(7) + "','" + list.get(8) + "','" + userid + "');";
String query1 = "INSERT INTO " + Table_values + " VALUES('" + plcData + "','" + agencyName + "','" + list1.get(0) + "','" + list1.get(1) + "','" + list1.get(2) + "','" + list1.get(3) + "','" + list1.get(4) + "','" + list1.get(5) + "','" + list1.get(6) + "','" + list1.get(7) + "','" + list1.get(8) + "','" + userid + "');";
String query2 = "INSERT INTO " + Table_ListId + " VALUES('" + plcData + "','" + agencyName + "','" + list2.get(0) + "','" + list2.get(1) + "','" + list2.get(2) + "','" + list2.get(3) + "','" + list2.get(4) + "','" + list2.get(5) + "','" + list2.get(6) + "','" + list2.get(7) + "','" + list2.get(8) + "','" + userid + "');";
try {
myDB.execSQL(query);
myDB.execSQL(query1);
myDB.execSQL(query2);
} catch(SQLException se) {
//do stuff when you catch a duplicate ID
}
I have to initialize a sqlite database that have a structure like this:
Table: Family
Table: SubFamily
Table: Product
One family can have more than one subfamily and and the same for subfamilies with products.
So what i'm doing is:
int index_family = 1;
int index_subfamily = 1;
int index_product = 1;
//Productos Familia Pavimentos
sqlDB.execSQL("INSERT INTO Family VALUES (" + index_family + ",'" + R.string.f1_pavimentos + "','" + R.string.f0_descripcion + "','" + R.drawable.color_pavimento + "');");
sqlDB.execSQL("INSERT INTO SubFamily VALUES (" + index_subfamily + "," + index_family + ",'" + R.string.f1s1_nivelantes + "','" + R.string.f0_descripcion + "','" + R.drawable.nivelante80 + "');");
sqlDB.execSQL("INSERT INTO Product VALUES (" + index_product + "," + index_subfamily + ",'" + R.string.f1s1p1_ni10 + "','" + R.string.f0_descripcion + "','" + R.drawable.nivelante80 + "','" + url + "');");
sqlDB.execSQL("INSERT INTO Product VALUES (" + (index_product + 1) + "," + index_subfamily + ",'" + R.string.f1s1p2_ni80 + "','" + R.string.f0_descripcion + "','" + R.drawable.nivelante80 + "','" + url + "');");
sqlDB.execSQL("INSERT INTO Product VALUES (" + (index_product + 2) + "," + index_subfamily + ",'" + R.string.f1s1p3_beL15 + "','" + R.string.f0_descripcion + "','" + R.drawable.nivelante80 + "','" + url + "');");
sqlDB.execSQL("INSERT INTO Product VALUES (" + (index_product + 3) + "," + index_subfamily + ",'" + R.string.f1s1p4_beL30 + "','" + R.string.f0_descripcion + "','" + R.drawable.nivelante80 + "','" + url + "');");
sqlDB.execSQL("INSERT INTO Product VALUES (" + (index_product + 4) + "," + index_subfamily + ",'" + R.string.f1s1p5_beP + "','" + R.string.f0_descripcion + "','" + R.drawable.nivelante80 + "','" + url + "');");
The problem is that the value of any index will increase all the time, and in a future will be added more products and families.
I want to know if there is some way more efficient that use for example this approach I did: (index_product + 1) ; (index_product + 2); ... without to use +N because in a future products (or families,subfamilies) will be added and deleted. And with a lot of products (more than 100) could be very dangerous this way.
Hope I explain my problem.
Judging from what your boss is saying, it might make more sense to have a table for products, sub families and what have you and use foreign keys to take care of everything. Thus, each parent will have a foreign key pointing to all their children.
If you use an ORM, this would very likely be done automatically behind the scenes.
Also as #Weston mentioned, avoid string concatenation within SQL statements. As is your application is prone to SQL injection.
I have tables in MySQL and did make connection with this database from Eclipse. I can insert my information into my tables in my MySQL database, but I want the code that can help me for I delete some information from there.
I have this code for inserting but I need the code for deleting:
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection connection = (Connection) DriverManager.
getConnection("jdbc:mysql://localhost/fish", "root", "test");
Statement s = (Statement) connection.createStatement();
s.executeUpdate("insert into fish.store(tr_no,tr_day,tr_month,tr_year,age_type," +
"class,pa_no,first_name,second_name,last_name,age,birth_place," +
" tele_no,address,gender,booking_status) values" +
"('" + fl_no + "','" + day + "','" + month + "','" +
year + "','" + age_type + "','" + fcl + "','" + spa + "'," +
"'" + sfirst + "','" + ssecond + "','" + slast + "','" + sage +
"','" + sP_O_B + "','" + sphone + "'," +
"'" + saddress + "','" + sgender + "','" + status + "')");
Ticket t = new Ticket(sfirst, slast, ssecond, ifl, fcl, day2, month2, year2);
t.setSize(830, 380);
t.setVisible(true);
t.setLocationRelativeTo(null);
t.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
ImagePanel panel = new ImagePanel(new ImageIcon("2.jpg").getImage());
t.getContentPane().add(panel);
} catch(SQLException ex) {
Logger.getLogger(fish.class.getName()).log(Level.SEVERE, null, ex);
}
You can use something like this:
//initialize connection...
String deleteString = "DELETE FROM fish.store WHERE first_name = ? AND last_name = ?";
PreparedStatement deleteStmt = null;
try {
//...
deleteStmt = connection.prepareStatement(deleteString);
deleteStmt.setString(1, "Clint");
deleteStmt.setString(2, "Eastwood");
deleteStmt.executeUpdate();
connection.commit();
} catch...
//close connection
Of course you have to replace the replacement of the statement with your own conditions (deleteStmt.set... (http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html)) and the WHERE clause of the SQL.
Have a look at http://dev.mysql.com/doc/refman/5.1/de/delete.html and http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
My Access Database memberID now is M15 , i want to get the next memberID M16 , how to get it and display in a text field ?
String query;
query = "INSERT INTO Membership VALUES ('" +memberID_a.getText() + "','" +memberName_a.getText() + "','" + icNo_a.getText() + "','" + gender_a.getText() +"','" + birthday_a.getText() +"','" + telephoneNo_a.getText() + "','" + mobileNo_a.getText() + "','" + email_a.getText() + "','" + address_a.getText() + "','" + postalCode_a.getText() + "','" + state_a.getText() + "','" + country_a.getText() + "','" + memberPoint_a.getText() + "');";
try{
stmtInsert = conn.createStatement();
stmtInsert.executeUpdate(query);
} catch(Exception ex){
JOptionPane.showMessageDialog(null,"ERROR"+ex.toString(),"ERROR",JOptionPane.ERROR_MESSAGE);
}
query = "INSERT INTO Membership VALUES ('" +memberID_a.getText() + "','" +memberName_a.getText() + "','" + icNo_a.getText() + "','" + gender_a.getText() +"','" + birthday_a.getText() +"','" + telephoneNo_a.getText() + "','" + mobileNo_a.getText() + "','" + email_a.getText() + "','" + address_a.getText() + "','" + postalCode_a.getText() + "','" + state_a.getText() + "','" + country_a.getText() + "','" + memberPoint_a.getText() + "');";
NEVER, EVER do that.
http://en.wikipedia.org/wiki/SQL_injection
instead use
query = "INSERT INTO Membership VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)";
Where each ? is a placeholder.
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
Anyway, the important thing to realise about database tables is that the order of the rows is meaningless unless you use an 'order by' clause in your query. So if you want to order by the id column, use
SELECT * from Membership ORDER BY id;