MySQL Query Through Java Syntax Error - java

I have this piece of code which inserts records into the accounts table:
String accNumber = jTextField5.getText();
String accName = jTextField4.getText();
String accAddress1 = jTextField3.getText();
String accAddress2 = jTextField2.getText();
String accCity = jTextField6.getText();
String accCounty = jTextField7.getText();
String accPostCode = jTextField9.getText();
String accContact = jTextField8.getText();
String query = "Insert into accounts (AccNo, name, address, address2, address3, City, County, PostCode, contact) values (?, ?, ?, ?, ?, ?, ?, ?, ?)";
try{
connect.pst = connect.con.prepareStatement(query);
connect.pst.setString(1, accNumber);
connect.pst.setString(2, accName);
connect.pst.setString(3, accAddress1);
connect.pst.setString(4, accAddress2);
connect.pst.setString(5, null);
connect.pst.setString(6, accCity);
connect.pst.setString(7,accCounty);
connect.pst.setString(8, accPostCode);
connect.pst.setString(9, accContact);
connect.pst.execute();
JOptionPane.showMessageDialog(null, "Saved");
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
This works just fine and inserts records into the accounts table. Next I have this piece of code which is meant to update the orderstable table which contains 6 fields; Order Number, AccNo, Incvoice Number, Description, Amount, VAT. The Order Number field has been set to auto increment
The code:
String accNumber = jTextField29.getText();
String invNo = jTextField20.getText();
String description = jTextField21.getText();
String vat = jTextField22.getText();
String amount = jTextField23.getText();
String query = "Insert into orderstable (Order Number, AccNo, Invoice Number, Description, Amount, VAT) values (?, ?, ?, ?, ?, ?)";
try{
connect.pst = connect.con.prepareStatement(query);
connect.pst.setString(1, "3");
connect.pst.setString(2, accNumber);
connect.pst.setString(3, invNo);
connect.pst.setString(4, description);
connect.pst.setString(5, amount);
connect.pst.setString(6, vat);
connect.pst.execute();
JOptionPane.showMessageDialog(null, "Saved");
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
This code above returns a SQL syntax error. I am not sure why. What could the reason be for this SQL syntax error?

You can not have the column names with space and if you do so you need to have then in backticks
Insert into orderstable
(`Order Number`, AccNo, `Invoice Number`, Description, Amount, VAT)
Check here for more details http://dev.mysql.com/doc/refman/5.0/en/identifiers.html

The auto increment field order number should not be include in the attribute section.
Your query should look like this
String query = "Insert into orderstable (AccNo, Invoice Number, Description, Amount, VAT) values (?, ?, ?, ?, ?)";
order number column should not be include in field list, because it is auto increment

Related

Prepared statement and serial data type

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 (?, ?, ?)";

How to getGenerated id from parent table and insert into child table

try {
currentCon = ConnectionManager.getConnection();
psParent=currentCon.prepareStatement("insert into accommodation (type,name,price,description,username)values(?,?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
psParent.setString(1,type);
psParent.setString(2,name);
psParent.setFloat(3,price);
psParent.setString(4,username);
psParent.executeUpdate();
accid= 0;
rs = psParent.getGeneratedKeys();
if (rs.next())
accid = rs.getInt(1);
rs.close();
psParent.close();
psChild=currentCon.prepareStatement("insert into room (accid, bed)values(?,?)");
psChild.setInt(1,accid);
psParent.setString(2,bed);
psChild.executeUpdate(); }
after I run this, I got this error message : failed: An Exception has occurred! java.sql.SQLRecoverableException: internal error
Is there's something wrong with the code? Thank you for your help
Your usage of getGenereatedKeys() actually looks correct to me for Oracle, but the problem is actually with your first insert statement. You have placeholders (and column names) for 5 columns, but you only bind 4 values. Try something like this:
String sql = "insert into accommodation (type, name, price, description, username) ";
sql += "VALUES (?, ?, ?, ?, ?)";
String generatedColumns[] = { "ID" };
psParent = currentCon.prepareStatement(sql, generatedColumns);
psParent.setString(1, type);
psParent.setString(2, name);
psParent.setFloat(3, price);
psParent.setString(4, description); // I ADDED THIS LINE
psParent.setString(5, username);
psParent.executeUpdate();
I am assuming that you have a variable containing a description to be inserted. If not, then remove description and its placeholder from the prepared statement entirely, or just insert null.

What is the explanation of this method using PreparedStatementCreator in Java?

I never used this class PreparedStatementCreator and normally when I want to execute a query I do something like: INSERT INTO table (a,b,c...) values (?,?,?...), but in this case the MySQL query is: INSERT INTO table() values() ??
Can you explain me that? I can't understand how the columns are tracked...
The following code is the method. Thanks in advance:
public String add(String identificationNumber, String firstName, String lastName, String email, String cellphone,
String city, String gender, BloodType bloodType, ShirtSize shirtSize, String emergencyContactName,
String emergencyContactPhone, String eps, Long birthday, Integer isVolunteer, Group group) {
PreparedStatementCreator psc = new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
String sql = "INSERT INTO participants() VALUES()";
return con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
}
};
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(psc, keyHolder);
String id = keyHolder.getKey().toString();
modify(id, identificationNumber, firstName, lastName, email, cellphone, city, gender, bloodType, shirtSize,
emergencyContactName, emergencyContactPhone, eps, birthday, isVolunteer);
if (group != null && !Utilities.emptyString(group.getId()))
setGroup(id, group);
return id;
}
public void modify(String id, String identificationNumber, String firstName, String lastName, String email,
String cellphone, String city, String gender, BloodType bloodType, ShirtSize shirtSize,
String emergencyContactName, String emergencyContactPhone, String eps, Long birthday, Integer isVolunteer) {
Object[] args = new Object[] { identificationNumber, firstName, lastName, email, cellphone, city, gender,
bloodType == null ? null : bloodType.toString(), shirtSize == null ? null : shirtSize.toString(),
emergencyContactName, emergencyContactPhone, eps, birthday, isVolunteer, id };
String sql = "UPDATE participants SET identificationNumber = ?, firstName = ?, lastName = ?, email = ?, cellphone = ?, city = ?, gender = ?, bloodType = ?, shirtSize = ?, emergencyContactName = ?, emergencyContactPhone = ?, eps = ?, birthday = ?, isVolunteer=? WHERE id = ?";
jdbcTemplate.update(sql, args);
}
You need to change following SQL :
String sql = "INSERT INTO participants() VALUES()";
Add Field name into participants() and add ? into VALUES().
Then you need to set the each ? value by following statements,
ps.setString(1, "test");
for each ? you need to set the values.
I hope this will work for you.
I finally got the answer to this, is very simple:
Inserts a row empty in the table.
Then gets the id of that row.
Calls modify to INSERT (really UPDATE the row).
That's all.

MySQL PreparedStatement: Parameter index out of range

I'v searched during one hour trough stackoverflow and couldn't find an answer to my problem (Well, there's people having the same error, but not exactly like mine).
So here's the code:
public synchronized static void setAllData(String player, String xp, String lvl, String coins, String won, String lost, String kills, String deaths, String redput, String blueput, String time)
{
try
{
PreparedStatement sql =
connection.prepareStatement("UPDATE `" + Main.table + "` SET `xp` = ?, lvl` = ?, `towercoins` = ?, `won` = ?, `lost` = ?, `kills` = ?, `deaths` = ?, `redput` = ?, `blueput` = ?, `time` = ? WHERE `player` = ?;");
sql.setString(1, xp);
sql.setString(2, lvl);
sql.setString(3, coins);
sql.setString(4, won);
sql.setString(5, lost);
sql.setString(6, kills);
sql.setString(7, deaths);
sql.setString(8, redput);
sql.setString(9, blueput);
sql.setString(10, time);
sql.setString(11, player);
sql.executeUpdate();
sql.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
And i have this error every time:
Java.sql.SQLException: Parameter index out of range (2 > number of
parameters, which is 1).
I don't get it since all parameters are here etc... so why ?
Thanks a lot :)
seems like you missing the opening quote on this statement.
SET `xp` = ?, lvl` = ?,
it would be like this
connection.prepareStatement("UPDATE " + Main.table + " SET xp = ?, lvl = ?, towercoins = ?, won = ?, lost = ?, kills = ?, deaths = ?, redput = ?, blueput = ?, time = ? WHERE player = ?;");

Cannot put entry in the mysql database

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 (?, ?, ?, ?, ?, ?, ?, ?, ?);" ;

Categories