Another MYSQL Issue - java

int rs2 = s
.executeUpdate("INSERT INTO hiscores (userid, playerRights, LVL, XP, 0, 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20) VALUES ('"
+ player.getUniqueId()
+ "', '"
+ player.getStaffRights()
+ "', '"
+ player.getSkill().getTotalLevel()
+ "','"
+ player.getSkill().getTotalXp()
+ "','"
+ player.getSkill().getExp()[0]
+ "','"
+ player.getSkill().getExp()[1]
+ "','"
+ player.getSkill().getExp()[2]
+ "','"
+ player.getSkill().getExp()[3]
+ "','"
+ player.getSkill().getExp()[4]
+ "','"
+ player.getSkill().getExp()[5]
+ "','"
+ player.getSkill().getExp()[6]
+ "','"
+ player.getSkill().getExp()[7]
+ "','"
+ player.getSkill().getExp()[8]
+ "','"
+ player.getSkill().getExp()[9]
+ "','"
+ player.getSkill().getExp()[10]
+ "','"
+ player.getSkill().getExp()[11]
+ "','"
+ player.getSkill().getExp()[12]
+ "','"
+ player.getSkill().getExp()[13]
+ "','"
+ player.getSkill().getExp()[14]
+ "','"
+ player.getSkill().getExp()[15]
+ "','"
+ player.getSkill().getExp()[16]
+ "','"
+ player.getSkill().getExp()[17]
+ "','"
+ player.getSkill().getExp()[18]
+ "','"
+ player.getSkill().getExp()[19]
+ "','"
+ player.getSkill().getExp()[20] + "')");
I am not sure why my code isn't working. I'm so close! Why am I getting an error with my syntax? It looks correct to me? Could anybody please help me with this? Any help is much appreciated!
fillerfillerfillerfillerfillerfillerfillerfillerfillerfillerfiller
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0, 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20) VALUES ('0', '0', '42','3' at line 1

I would use a PreparedStatement in this case to simplify this code:
PreparedStatement st;
st = connection.prepareStatement(""
+"INSERT INTO hiscores (userid, playerRights, LVL, XP, "
+"`0`,`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`10`,`11`,`12`,`13`,`14`,`15`,"
+"`16`,`17`,`18`,`19`,`20`) "
+"VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
st.setInt( 1, player.getUniqueId());
st.setString( 2, player.getStaffRights());
st.setInt( 3, player.getSkill().getTotalLevel());
st.setString( 4, player.getSkill().getTotalXp());
for(int i=0; i<=20; i++){
st.setInt( i+5, player.getSkill().getExp()[i]);
}
st.executeUpdate();

Related

inserting to database using java gui

I am trying to insert data from my netbeans to mysql workbench. there is no problem with the query but when I run the program a message box appear "Unknown column 'empJob' in 'field list '" . What seems to be the problem?
and just to Know i tried this on another table and it works just fine! but in this one it doesn't work!
int id, Salary;
String name, Address, Jop;
id = Integer.parseInt(tNo.getText());
name = tName.getText();
Address = tAddress.getText();
Jop = tJop.getText();
Salary = Integer.parseInt(tNo.getText());
String sql = "insert into employee(empid,empName, empAddress,empJob,empSalary) values('" + id + "','" + name + "' , '" + Address + "','" + Jop + "','" + Salary + "')";
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
int x = st.executeUpdate(sql);
if (x > 0) {
JOptionPane.showMessageDialog(prev, x + "rows effected");
} else {
JOptionPane.showMessageDialog(prev, "insert failed");
}
Do you have a typo? You write empJob -> but your variable is called Jop. So maybe it should be empJop.
String sql = "insert into employee(empid,empName, empAddress,empJop,empSalary) values('" + id + "','" + name + "' , '" + Address + "','" + Jop + "','" + Salary + "')";

Sqlite Constraint Exception error

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
}

How to use int and increase it's value in different code lines

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.

MySQL deleting code data in Eclipse

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

Get the next ID in Access database(now the ID is M15, i want get M16)

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;

Categories

Resources