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();
}
Related
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();
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.
So my issue is after I insert a new record in the database, I want to do a SELECT query that should include that new record. However, the data being returned excludes the newly added record. It seems like whenever I first open the connection, whatever is already in the database is what my program goes off. I hope this makes sense. All input is appreciated.
Update:
So here is the INSERT snippet
String DML = "INSERT INTO MEMBERS (FIRST_NAME, LAST_NAME, BIRTHDATE, DEATH_DATE, MARITAL_STATUS,"
+ " WEDDING_DATE, SPOUSE_NAME, MILITARY_SERVICE, DATE_JOINED, DEPARTURE_DATE, ACCEPTANCE_MODE, DEPARTURE_MODE,"
+ " RELATED_TO, NOTES) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(DML);
pstmt.setString(1, jTextField2.getText());
pstmt.setString(2, jTextField1.getText());
pstmt.setString(3, jTextField6.getText());
pstmt.setString(4, jTextField11.getText());
pstmt.setString(5, jTextField3.getText());
pstmt.setString(6, jTextField5.getText());
pstmt.setString(7, jTextField4.getText());
pstmt.setString(8, jTextField8.getText());
pstmt.setString(9, jTextField7.getText());
pstmt.setString(10, jTextField10.getText());
pstmt.setString(11, jTextField9.getText());
pstmt.setString(12, jTextField13.getText());
pstmt.setString(13, jTextField14.getText());
pstmt.setString(14, jTextArea1.getText());
pstmt.executeUpdate();
if (conn.getAutoCommit() == false)
conn.commit();
Now this is the SELECT snippet which if fired after the INSERT
pstmt=conn.prepareStatement("SELECT CONCAT(LAST_NAME, ', ', FIRST_NAME) AS NAME FROM MEMBERS ORDER BY LAST_NAME, FIRST_NAME");
rs=pstmt.executeQuery();
It is very likely that you have autocommit mode disabled and/or you are running the 2 queries (INSERT then SELECT) as a transaction.
Try turning autocommit mode on and then running the 2 queries again (INSERT then SELECT), it should work.
If you mean this
stmt.executeUpdate("insert into t1 ...");
ResultSet rs = stmt.executeQuery("select ... from t1");
then data inserted in statement 1 is always visible in statement 2, both in autocommit on and off modes.
It is only possibly that select does not see inserted records if you insert in one transaction, do not commit, and read in another transaction
Something like this can be done:
You can use an autoincrement column say call it serialID.
Insert data normally. When retrieving use MAX(serialID)
SELECT CONCAT(LAST_NAME, ', ', FIRST_NAME) AS NAME FROM MEMBERS ORDER BY
LAST_NAME, FIRST_NAME where serialID = (select max(serialID) from MEMBERS);
You'll have to do this in one transaction.
private void B_save_pActionPerformed(java.awt.event.ActionEvent evt) {
try{
String db = "jdbc:mysql://localhost/ar";
Connection con = DriverManager.getConnection(db, "rehan", "1234");
PreparedStatement ps;
String sql = "INSERT INTO purchase (item_type, md_by, model, selling_price, purchase_price, purchase_date, item_image, vouch_no, vouch_date) VALUES ('?', '?', '?', ?, ?, '?', ?, ?, '?');" ;
ps = con.prepareStatement(sql);
ps.setString(1 , txt_itype_p.getText());
ps.setString(2, txt_md_by_p.getText());
ps.setString(3, txt_model_p.getText());
ps.setString(4, txt_s_price_p.getText());
ps.setString(5 , txt_p_price.getText());
ps.setString(6, null);
ps.setString(7, null);
ps.setString(8, txt_vouch_p.getText());
ps.setString(9 , null);
ps.execute();
}
catch(SQLException ex){
JOptionPane.showMessageDialog(null, ex);
}
DefaultTableModel tblModel = (DefaultTableModel) Table_p.getModel();
if(!txt_itype_p.getText().trim().equals("")) {
tblModel.addRow(new Object[]{tbl_sr, txt_itype_p.getText(),txt_model_p.getText(),txt_md_by_p.getText(),txt_date_p.getText(),txt_p_qty.getText(),txt_p_price.getText(),txt_s_price_p.getText()});
txt_itype_p.setText(null);
txt_ipath.setText(null);
txt_itype_p.setText(null);
txt_md_by_p.setText(null);
txt_model_p.setText(null);
txt_p_date.setText(sdf.format(date));
txt_p_price.setText(null);
txt_p_qty.setText(null);
txt_s_price_p.setText(null);
}
tbl_sr = tbl_sr +1;
saved = true;/*If someone accidently click the close button, system will
confirm while getting the value of this bolean variable*/
}
This is my code for the save button which is supposed to show the entries on a JTable in a JFrame and also saves the entries into mysql database in 'purchase' table, but the problem is it shows the entries on the JTable but doesnot saves in database. I have same code to create new users which saves username, password and account type in the login table in database and that code is working fine. I have a feeling that this problem is due to some data types issue but i am not confirmed.
I am using Netbeans and mysql database. I tried to send 'null' to date and image data types but still its not working.
Someone please help me.
This line has a problem:
String sql = "INSERT INTO purchase (item_type, md_by, model, selling_price, purchase_price, purchase_date, item_image, vouch_no, vouch_date) VALUES ('?', '?', '?', ?, ?, '?', ?, ?, '?');" ;
The problem is the five ?s that are surrounded by single quotes. JDBC does not recognise these as placeholders and assumes you want to insert a string containing just a ? character into the item_type, md_by, model, purchase_date and vouch_date columns.
The fix is to remove all of the single quotes around the ? marks:
String sql = "INSERT INTO purchase (item_type, md_by, model, selling_price, purchase_price, purchase_date, item_image, vouch_no, vouch_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);" ;
I still get error that I don't provide value for 1 parameter and I don't have idea what is wrong.
ps("INSERT INTO slide (presentation_id, duration, position, type) values (?, ?, ?, ?) ").set(this.getId()).set(slide.getDuration()).set(slide.getPosition()).set(slide.getType().ordinal()).update();
In table I only do not provide value for one column for which autoincrement is set.
Everything seems alright for me but please give any advice what might be wrong.
dont include the auto inc fieldin your column list.
ps("INSERT INTO slide (duration, position, type) values (?, ?, ?) ").set(slide.getDuration()).set(slide.getPosition()).set(slide.getType().ordinal()).update();
Try to do something more clean instead of this "train code"
This is an example:
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "mkyong");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
// execute insert SQL stetement
preparedStatement .executeUpdate();
and here is the link to follow: http://www.mkyong.com/jdbc/jdbc-preparestatement-example-insert-a-record/