I was trying to use java to insert some data into mysql database, but it kept giving syntax error:
Exception in thread "main" 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 ' postcode ='n'' at line 1
here is my code:
`
public static void saveAddress(Address address) throws SQLException{
SQLConnection sql = new
SQLConnection(SQLConnection.getConnection());
if(SQLAddress.getAddressID(address) == -1){
sql.update(String.format("INSERT INTO address(houseNumber,
street, district, city, postcode) VALUES (%s ,%s ,%s ,%s
,%s)",address.getHouseNumber(),address.getStreet(),
address.getDistrict(),address.getCity(),
address.getPostCode()));
}
sql.close();
}
`
I really don't know what to do, i used the same syntax in mysql shell, it worked perfect there.
Edit
public static void saveAddress(Address address) throws SQLException{
Connection sql = SQLConnection.getConnection();
if(SQLAddress.getAddressID(address) == -1){
PreparedStatement ps = sql.prepareStatement("INSERT INTO address (houseNumber, street, district, city, postcode) VALUES (?, ?, ?, ?, ?);");
ps.setString(1, address.getHouseNumber());
ps.setString(2, address.getStreet());
ps.setString(3, address.getDistrict());
ps.setString(4, address.getCity());
ps.setString(5, address.getPostCode());
ps.executeUpdate();
sql.commit();
}
sql.close();
}
You should be happy that you ran into this error, because if it didn't happen, you'd create a huge security problem. Inserting user values into SQL string enables SQL injection attacks, which is a very dangerous possibility.
Switch to using prepared statements, and bind parameters to them. This is similar to the way you did with formatting, but it's done on separate lines:
PreparedStatement upd = sql.prepareStatement("INSERT INTO address(houseNumber, street, district, city, postcode) VALUES (?, ?, ?, ?, ?)");
upd.setInt(1, address.getHouseNumber());
upd.setString(2, address.getStreet());
... // Set other fields
upd.executeUpdate();
sql.commit();
Related
This is my PostgreSQL code:
CREATE TABLE "user" (
id serial UNIQUE,
username varchar,
password varchar,
email varchar,
);
I want to create Java method, which adds new user to my table user:
public static void addUser(Connection con) throws SQLException {
String sql = "INSERT INTO user VALUES (?, ?, ?)";
try(PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, "test");
ps.setString(2, "test");
ps.setString(3, "test#email.com");
ps.executeUpdate();
}
}
}
Because column id is serial, I don't create prepared statement for this column (even without java, I would make insert only with remaining values, since id would be generated automatically). Hovewer, when I run this code, I get the following error:
ERROR: column "id" is of type integer but expression is of type character varying
What am I doing wrong?
Always specify the target columns in an INSERT statement. And as user is a reserved keyword, you have to quote it (but it would be better if you found a different name)
String sql = "INSERT INTO \"user\" (username, password, email) VALUES (?, ?, ?)";
Here is the code:
String sqlstatment = "INSERT INTO order (orderedBy, totalItems, totalPrice) "+
"VALUES (?, ?, ?);";
ResultSet keys = null;
try (
PreparedStatement stmt = conn.prepareStatement(sqlstatment, Statement.RETURN_GENERATED_KEYS);
){
stmt.setInt(1, 1);
stmt.setInt(2, 3);
stmt.setInt(3, 5);
int affected = stmt.executeUpdate();
if (affected == 1){
keys = stmt.getGeneratedKeys();
keys.next();
int newKey = keys.getInt(1);
orderBean.setOrderID(newKey);
}else{
System.out.println("An Error has ocurred while creating the Order.");
}
}catch (SQLException e){
System.err.println(e.getMessage());
}finally{
if (keys != null) keys.close();
}
And when I run the code I get this error:
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 'order (orderedBy, totalItems, totalPrice) VALUES (1, 3, 5)' at line 1
I'm not entirely sure why I get the error so if you know that would be great.
order is a reserved word, try
String sqlstatment = "INSERT INTO \"order\" (orderedBy, totalItems, totalPrice) "+
"VALUES (?, ?, ?);";
Your query contains a RESERVED KEYWORD order as your table name. MySQL documentation clearly suggests that use of such keywords should always be avoided, if they need to be used then it has to be with the use of backticks as shown below '`'.
Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.
Your query that gets assigned to a String in turn should be changed to the following to resolve this error!
"INSERT INTO \"order\" (orderedBy, totalItems, totalPrice) VALUES (?, ?, ?);"
The following is a documentation link to the reserved keywords for MySQL -> Documentation
Hope this helps!
How do I check if the statement can execute in my code? the second parameter won't be set if txtFirstName.getText() is empty.
String sql = "INSERT INTO Employees (id, firstName, lastName, adress, phone, email, photo, comments) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement statement = database.connection.prepareStatement(sql);
statement.setString(1, database.users.size() + 1 + "");
if (txtFirstName.getText().matches(""))
statement.setString(2, txtFirstName.getText());
statement.setString(3, txtLastName.getText());
statement.setString(4, txtAdress.getText());
statement.setString(5, txtPhone.getText());
statement.setString(6, txtEmail.getText());
statement.setString(7, txtPhotoURL.getText());
statement.setString(8, txtComment.getText());
statement.executeUpdate();
the second parameter won't be set if txtFirstName.getText() is empty.
Yes, it will; it will be set to an empty string. Whether that's valid for this specific query and table structure is beyond the realm of JDBC.
You need to check your constraints in advance, separately, and then either make the call or not.
You need an else condition to specify what to do if txtFirstName does not match the pattern, e.g.:
if (txtFirstName.getText().matches("")){
statement.setString(2, txtFirstName.getText());
}else {
throw new IllegalArgumentException("Invalid name pattern");
}
This will prevent the code from executing errorneous preparedstatement and throw an exception with appropriate error message.
I have an "Invitation" object that is modeled in a MySQL database. This object has one list ("treatmentPlanIDsToCopyf") and is maintained in the database with a second table. The method I have written to insert into the main table and then loop through the list and insert records for each item in the list into the second table is below. At the line ps = cn.prepareStatement(sql);Eclipse is giving me a warning that says "Resource leak: 'ps' is not closed at this location". I am closing the prepared statement in the finally clause, so I wanted to know if there really is a resource leak I need to fix. This is my first time using batches with prepared statements, so I wasn't really sure. Thanks.
public void invitationCreate(Connection cn, Invitation invitation) throws SQLException{
PreparedStatement ps = null;
try {
//first insert primary invitation data into the invitation table
String sql = "INSERT INTO invitiation (invitation_code, recipient_email, sender_user_id_fk, date_intived, date_accepted, accepted, recipient_first_name, recipient_last_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
ps = cn.prepareStatement(sql);
ps.setString(1, invitation.getInvitationCode());
ps.setString(2, invitation.getRecipientEmail());
ps.setInt(3, invitation.getSenderUserID());
ps.setTimestamp(4, convertLocalTimeDateToTimstamp(invitation.getDateInvited()));
ps.setTimestamp(5, convertLocalTimeDateToTimstamp(invitation.getDateAccepted()));
ps.setBoolean(6, invitation.isAccepted());
ps.setString(7, invitation.getRecipientFirstName());
ps.setString(8, invitation.getRecipientLastName());
int success = ps.executeUpdate();
//now loop through all the treatmentPlanIDs in the invitation that are to be copied into the invitees account when the register
sql = "INSERT INTO invitation_treatment_plans (invitation_code_fk, invitation_treatment_plan_id_fk) VALUES (?, ?)";
ps = cn.prepareStatement(sql);//TODO confirm this if this is actually a resource leak
for(int treatmentPlanID : invitation.getTreatmentPlanIDsToCopy()){
ps.setString(1, invitation.getInvitationCode());
ps.setInt(2, treatmentPlanID);
ps.addBatch();
}
ps.executeBatch();
} finally {
DbUtils.closeQuietly(ps);
}
}
I believe the leak is in the first prepared statement.
After int success = ps.executeUpdate(); you need to close that prepared statement before you assign the variable to a new prepared statement.
I tried to do this:
query1="INSERT INTO `users`(`email`, `password`, `login`, `familiya`, `name`, `otchestvo`, `age`, `country`, `city`, `mob`, `skype`) VALUES ("+user.getEmail()+","+user.getPassword()+","+user.getLogin()+","+user.getFamiliya()+","+user.getName()+","+user.getOtchestvo()+",11,"+user.getCountry()+","+user.getCity()+","+user.getMob()+","+user.getSkype()+")";
what did I do wrong? All "get" is not null, only syntax error.
I want to post image of database but I need 10 reputation...
all fields are varchar(15), age is int(2)
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 '#mail.ru,12345,dima,Dmitriev,dima,Dmitrievich,11,Dmitrountry,Dmitriegrad,2020327' at line 1
put single quotes " ' " around your string values (varchar, text etc)
so
String query1="INSERT INTO users(email, password, login, familiya, name, otchestvo, age, country, city, mob, skype) VALUES ('"+user.getEmail()+"','"+user.getPassword()+"','"+user.getLogin()+"','"+user.getFamiliya()+"','"+user.getName()+"','"+user.getOtchestvo()+"',11,'"+user.getCountry()+"','"+user.getCity()+"','"+user.getMob()+"','"+user.getSkype()+"')";
not string related types DON't get single quotes....
A better way to do this however is using PreparedStatement,
String sql = "INSERT INTO users(email, password, login, familiya, name, otchestvo, age, country, city, mob, skype) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement preparedStatement = con.prepareStatement(sql)) {
preparedStatement.setString(1, user.getEmail);
preparedStatement.setString(2, user.getPassword);
preparedStatement.setString(3, user.getLogin());
preparedStatement.setString(4, user.getFamiliya());
preparedStatement.setString(5, user.getName());
preparedStatement.setString(6, user.getOtchestvo());
preparedStatement.setInt(7, 11);
preparedStatement.setString(8, user.getCountry());
preparedStatement.setString(9, user.getCity());
preparedStatement.setString(10, user.getMob());
preparedStatement.setString(11, user.getSkype());
preparedStatement.executeUpdate();
}