I have a MySQL Table which looks like this:
I made some Textfields in my form and saved the input as Strings:
String name = shopname.getText();
String address = streetaddress.getText();
String city = cityname.getText();
String state = statename.getText();
String country = countryname.getText();
String zip = zipcode.getText();
String phonept1 = phonecountryid.getText();
String phonept2 = phoneareaid.getText();
String phonept3 = phoneothernumber.getText();
String phonefull = phonept2 + " " + "(" + phonept1 + ")" + " " + phonept3;
Then I just made an INSERT method which worked well with the old SQLite Database:
conn = DBConnect.Connector();
stmt = conn.createStatement();
stmt.executeUpdate("INSERT INTO shopList (name,address,city,state,country,zipcode,phonefull) VALUES(" +name+ "," + address + "," + city + "," + state + "," + country + "," + zip + "," + phonefull + ")");
conn.close();
But now it says:
SEVERE: null
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 '(22) 222222)' at line 1
Anyone see the syntax error?
ps. (22) 222222 is the tested phonefull input.
conn = DBConnect.Connector();
stmt = conn.createStatement();
stmt.executeUpdate("INSERT INTO shopList (name,address,city,state,country,zipcode,phonefull) VALUES('" +name+ "','" + address + "','" + city + "','" + state + "','" + country + "','" + zip + "','" + phonefull + "')");
conn.close();
Try this (I have wrapped your string VALUES in single quotes)
edit:
You are leaving yourself vulnerable to SQL injections by passing string values directly. When possible you want to use the PreparedStatement object and setString method.
Related
I'm having problem with the uniqueidentifier from MySQL which is when i tried to insert an array of data into a table that has a uniqueidentifier datatype in one of the column, it just says conversion failed when converting string to uniqueidentifier.
Here's MySQL block:
if (Gender.trim().equals(""))
z = "Value not enough";
else {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
final String query = "USE [dbtest]" +
"insert into [tablename] ([DepositorID],[Name],[Sex],[DateOfBirth],[Race],[Occupation],[Occupation_others],[AddressLine1],[AddressLine2],[Postcode]," +
"[City],[State],[AgeSah],[TelNo],[HPNo],[Email],[Bank],[BankNo],[CreatedBy],[CreatedOn],[ModifiedBy],[ModifiedOn]) values " +
"('" + nokppv + "','" + Namev + "','" + sex + "','" + Date + "','" + Race + "','" + Occupation + "','" + Occupation2 + "','" + Address + "','" + Address2 +
"','" + Postcode + "','" + City + "','" + State + "','" + agesah + "','" + telno + "','" + Phonev + "','"+ Email +"','"+ Bank +"','"+ BankNo +
"',' "+ chars +"','"+ CreatedOn +"','"+ chars1 +"','" + ModifiedOn + "')";
System.out.println("Query:"+query);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs.next()){
z = "Registration successful";
isSuccess = true;
}else {
z = "Registration error";
isSuccess = false;
}
}
} catch (Exception ex) {
isSuccess = false;
z = "Exceptions";
System.err.println("Message:"+ex.getMessage());
System.err.println("Cause:"+ex.getCause());
System.out.println("Query:"+query);
}
}
}
return z;
}
The things that I already tried
The column for uniqueidentifier allows null and tried to insert it null, same error.
Tried android GUID code, same error, found out sql server uid are sequential which is different from java uid.
Tried declaring UniqueIdentifier variable from JDBC library, same error.
I did found some post that mention of UID generator thats generate a sequential UID that compatible to SQL UID datatype but the post answer was very vague.
I just need hints or a few example to make my own code I hope I provide enough data. Anyone willing to show me the rope around? BTW I'm using MSSQL 2016
and using Android Studio as Java platform.
Try :
+"CONVERT(uniqueidentifier,'"+chars+"' )"
+"CONVERT(uniqueidentifier,'"+chars1+"' )"
You should get :
values ('840403055141','Shariffah Saralisha binti Syed Ali','P','04-03-1984','K','015','null','No 43, Jalan valera 1/3, Taman Tingtong','null','43900','Sepang','K','Y','null','0123456789','Demo#emailhost.com','123','123',CONVERT(uniqueidentifier,'55555555-2222-2222-2222-222222222222'),'2017-02-16 19:59:22','CONVERT(uniqueidentifier,'22222222-2222-2222-2222-222222222222'),'null')
I'm trying to get the integer(age information) in my SQL query using this method
// ...
Integer age = 42;
String sql = "insert into user_info value('" + username + "','" + passcode + "','" + gender + "',age,'" + email + "')";
try {
PreparedStatement preparedStatement = con.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
try {
i = stmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
finally i got the result of successfully inserting all the information, username, passcode, gender and email, but for the AGE info, it just shows NULL in my mysql database table, and i have tried so hard to fix this but still got confused, please help me out, thx:)
Correct your code first to and then try.
gender + "'," + age + ",'" + email
Secondly you are not using PreparedStatement in right manner. In PreparedStatement you set the dynamic values and do concatenate the SQL like this. Check this https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html
You got an error in you sql query
String sql = "insert into user_info value('" + username + "','" + passcode + "','" + gender + "',age,'" + email + "')";
This will not insert the age value, so age will be set to his default value (NULL)
Try with this query
String sql = "insert into user_info value('" + username + "','" + passcode + "','" + gender + "','" + age + "','" + email + "')";
I am trying to read from a mysql table and I am doing the following:
protected void pushRegisteredStudentsData() {
try {
conn = (Connection) DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String userID = "SELECT * FROM STUDENT";
rs = stmt.executeQuery(userID);
while (rs.next()) {
int id = rs.getInt("ID");
this.studentID = id;
String insertSql = "INSERT INTO REGISTEREDSTUDENTS(StudentID, ModuleCode) VALUES ('" + studentID + "', + '"
+ this.moduleCode + "')";
System.out.println("Inserting into REGISTEREDSTUDENTS.. [" + id + "]" + "[" + this.moduleCode + "]");
stmt.executeUpdate(insertSql);
}
} catch (SQLException e) {
}
}
..but for some reason,
while (rs.next()) {
int id = rs.getInt("ID");
always returns the same ID, even though the table has different ID's on every line!
Does anyone have an idea why that might be?
Thank you in advance! :(
EDIT:
I was using a single statement to execute 2 updates, which was causing the problem!
It is a bit weird that it returns always the same value because it should only return the first value ONCE.
If you print the stacktrace instead of just catching the exception and doing nothing, you will see that it will print something like:
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:794)
You are using THE SAME statement for a Select and then for an Insert. This causes the resultSet that is "attached" to the Statement to close because it is not supposed to be used again.
It can be easily fixed by creating another statement:
String insertSql = "INSERT INTO REGISTEREDSTUDENTS(StudentID, ModuleCode) VALUES ('" + studentID + "', + '"
+ this.moduleCode + "')";
System.out.println("Inserting into REGISTEREDSTUDENTS.. [" + id + "]" + "[" + this.moduleCode + "]");
Statement stmt2 = conn.createStatement();
stmt2.executeUpdate(insertSql);
I am writing the following SQL query in my Java program
PreparedStatement pre = conn.prepareStatement("select ID,FirstName,LastName,Dept from "
+ "student where ID =" + ID + " or FirstName=" + firstName + ";");
However, I am getting the following error:
use the right syntax for FirstName="+Parker
How is this caused and how can I solve it?
You should take advantage of prepared statements by making use of prepared statements parameters. This way, you can set your parameters pragmatically using setters.
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html.
Here is a snippet from the Oracle docs:
PreparedStatement updateSales = null;
String updateString = "update " + dbName + ".COFFEES " + "set SALES =
? where COF_NAME = ?";
updateSales = con.prepareStatement(updateString);
updateSales.**setInt**(1, e.getValue().intValue());
updateSales.**setString**(2, e.getKey());
Just make sure you set the statements *in order a*s the sql query.
Use a PreparedStatement like this:
PreparedStatement pre = conn.prepareStatement("select ID,FirstName,LastName,Dept from student where ID = ? or FirstName = ?");
pre.setInt(1, ID);
pre.setString(2, firstName);
I haven't used sql in Java, but my guess is it is because you don't have single quotes around first name. You want:
PreparedStatement pre = conn.prepareStatement("select ID,FirstName,LastName,Dept from " + "student where ID =" + ID + " or FirstName='" + firstName + "';");
emphasis:
... FirstName='" + firstName + "';");
I have the following string which holds the query I want to execute:
query = "UPDATE inventario"
+ " set descripcion = '" + descripcion + "',"
+ " set bodega = '" + bodega + "'"
+ " where codigo = " + codigo;
I get an Update statement syntax error but I dont see where is the error. Any help is appreciated.
columns "descripcion" and "bodega" are text type columns.
Well it's probably because you've got multiple set parts instead of using comma separation, and potentially because you don't have quotes around the codigo value (if that's another string)... but I'd strongly advise you not to create SQL like this anyway, with values directly in the SQL.
Instead, use a prepared statement:
String sql = "UPDATE inventario set descripcion=?, bodega=? where codigo=?";
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, descripcion);
st.setString(2, bodega);
st.setString(3, codigo);
Using prepared statements has three immediate benefits:
It avoids SQL injection attacks (think about what happens if your description has a quote in it)
It separates code (SQL) from data (the values)
It means you avoid conversions for types like datetime, where going via a string representation is a huge potential source of error
Remove extra SET on your query.
query = "UPDATE inventario"
+ " set descripcion = '" + descripcion + "',"
+ " bodega = '" + bodega + "'"
+ " where codigo = " + codigo;
but that query is vulnerable with SQL Injection. Please parameterize your query.
Example,
String query = "UPDATE inventario" +
" set descripcion = ?, bodega = ? " +
" where codigo = ?";
PreparedStatement prep = connection.prepareStatement(query);
prep.setString(1, descripcion);
prep.setString(2, bodega);
prep.setInt(3, codigo);
prep.executeUpdate();
SET keyword is needed only once. Multiple columns that are being updated should be separated by commas, as in the below statement.
query = "UPDATE inventario"
+ " set descripcion = '" + descripcion + "',"
+ " bodega = '" + bodega + "'"
+ " where codigo = " + codigo;
BTW, it is highly recommended to use PreparedStatement for such operations instead of forming the query like this to avoid SQL Injection attacks.
query = "UPDATE inventario"
+ " set descripcion = ?, bodega = ? "
+ " where codigo = ?";
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, descripcion);
ps.setString(2, bodega);
ps.setInt(3, codigo);
int updateCount = ps.executeUpdate();