I'm currently facing a problem with my SQL query using a prepared statement.
String test= "INSERT INTO TEST" + "(ID, IC, CN, CT, Time)"
+ "VALUES ('"+ ID +"','"+ IC +"','"+CN +"','"+ CT +"','"+ time +"')";
preparedStatement = myConn.prepareStatement(test);
preparedStatement.executeUpdate();
I have successfully connected to the database, and the table is created out. Is it because of the single quotation problem?
You're missing the point of using a PreparedStatement. You could just bind the values so you don't have to mess around with quoting yourself:
String test= "INSERT INTO TEST (ID, IC, CN, CT, Time) VALUES (?, ?, ?, ?, ?)";
preparedStatement = myConn.prepareStatement(test);
preparedStatement.setString(id);
preparedStatement.setString(ic);
preparedStatement.setString(cn);
preparedStatement.setString(ct);
preparedStatement.setDate(new Timestamp(time));
preparedStatement.executeUpdate();
I am trying to insert into a vehicle table using a prepared statement. This is the table shown in PHPMyAdmin.
This is my java code
try {
String sql = "INSERT INTO vehicle (vin, serial, make, model, year, reg.no., status) VALUES (?, ?, ?, ?, ?, ?, ?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, vin);
statement.setString(2, serial);
statement.setString(3, make);
statement.setString(4, model);
statement.setInt(5, 10);
statement.setInt(6, 17);
statement.setString(7, status);
System.out.println(statement.toString());
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A new user was inserted successfully!");
}
} catch (Exception ex) {
System.out.println(ex);
}
and this is the resulting error
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' status) VALUES ('dfg', 'dfgfg', 'fg', 'sd564', 10, 17, 'dsf')' at line 1
I am clueless. Does it have to do with me not passing a value for the primary key "id" column in the table?
reg.no. isn't a valid column name. If you really need to use it, you should quote it:
INSERT INTO vehicle (vin, serial, make, model, year, `reg.no.`, status)
-- Here ---------------------------------------------^-------^
VALUES (?, ?, ?, ?, ?, ?, ?)";
Can anyone help me out please? I am trying to retrieve ID(primary key) at the time the record is created and set it to a textfield. Currently, all it returns is 1 all the time.
My current approach looks like this:
connection = Utilities.getConnection();
String sqlQuery = "INSERT INTO student_details (Name, Surname, Date_Of_Birth, Gender, Address, Post_Code, Mobile_Number)" + " VALUES (?, ?, ?, ?, ?, ?, ?)";
preparedStatement = connection.prepareStatement(sqlQuery);
preparedStatement.setString(1, txtFirstName.getText().trim());
preparedStatement.setString(2, txtSurname.getText().trim());
preparedStatement.setString(3, String.valueOf(dpDateOfBirth.getValue()));
preparedStatement.setString(4, cbGender.getSelectionModel().getSelectedItem().toString());
preparedStatement.setString(5, txtAddress.getText().trim());
preparedStatement.setString(6, txtPostCode.getText().trim());
preparedStatement.setString(7, txtMobileNo.getText().trim());
preparedStatement.executeUpdate();
txtStudentID.setText(String.valueOf(preparedStatement.RETURN_GENERATED_KEYS));
Utilities.showInforMsg("Record Saved:", "Record has been saved.");
You should get the generated key via:
ResultSet rs = preparedStatement.getGeneratedKeys();
if (rs.next()) {
key = rs.getLong(1);
}
what you are doing with this line
txtStudentID.setText(String.valueOf(preparedStatement.RETURN_GENERATED_KEYS));
is setting the student id to the value of the constant of the Statement interface (see here https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#RETURN_GENERATED_KEYS)
I'm doing this:
String columns = "UserHash,EMail,Name,Gender,BirthYear,Birthday,MaritalStatus,UserID,ReferralUser,Likes";
String sql = "INSERT INTO Users ("+ columns+") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
byte[] bytesOfUserHash = user.getId().getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] userHash = md.digest(bytesOfUserHash);
stmt = con.prepareStatement(sql);
stmt.setBytes(1,userHash);
stmt.setString(2, user.getEmail());
stmt.setString(3, user.getName());
stmt.setInt(4, user.getGender().value());
stmt.setString(5, birthday.split("-")[0]);
stmt.setString(6, birthday);
stmt.setInt(7, user.getRelationshipStatus().value());
stmt.setString(8, user.getId());
stmt.setString(9, referraluser);
stmt.setString(10, likesjson);
stmt.executeUpdate();
All values are being inserted except for userHash, so the query is succeeding. What should I check?
Also, note I'm just hashing the userid right now, but I would like to hash the userid + CURRENT_TIMESTAMP.
UPDATE:
As a sanity check, I just tried tossing a string into the UserHash column as it is of type VARCHAR(45) and that's not working either. Something is obviously amiss independent of the MD5 issue.
You can use MySQL's built in MD5 function and only pass userId as parameter
String sql = "INSERT INTO Users ("+ columns+") VALUES (MD5(CONCAT(?,CURRENT_TIMESTAMP), ?, ?, ?, ?, ?, ?, ?, ?, ?);";
stmt = con.prepareStatement(sql);
stmt.setInt(1,user.getId());
...
how can i write prepared statement instead of this: please help me
String qry= "INSERT INTO
Registration1(RegistrationNo,Date,SeniorPerson,NativePlace,Kul,Gotra,KulSwami,ResidensialAddress,PinCode,STDcode,TelephoneNo,MobileNo,Email,Website,Education,Branch,BirthDate,BloodGroup) VALUES('"+regno+"','"+dt+"','"+nm+"','"+place+"','"+kul+"','"+gotra+"','"+kswami+"','"+raddr+"','"+pincode+"','"+stdcd+"','"+tele+"','"+mno+"','"+email+"','"+website+"','"+education+"','"+branch+"','"+bdt+"','"+bloodgrp+"')";
stmt.executeUpdate(qry);
PreparedStatement stmt = conn.prepareStatement("INSERT INTO Registration1(RegistrationNo,Date,SeniorPerson,NativePlace,Kul,Gotra,KulSwami,ResidensialAddress,PinCode,STDcode,TelephoneNo,MobileNo,Email,Website,Education,Branch,BirthDate,BloodGroup) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
int col = 1;
stmt.setString(col++, regno);
stmt.setDate(col++, new java.sql.Date(dt.getTime())); // assuming dt is a java.util.Date
(etc)
stmt.executeUpdate();
`enter code here`you can use prepared statement of insertion like..
Connection MyCon=null;
PreparedStatement Ps=null;
try{
myCon=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","student","student");
// these are string from where we can take inputs .
String Fname;
String Lname;
String email;
String department;
String Salary;
Fname=JOptionPane.showInputDialog(null,"Enter First Name");
Lname=JOptionPane.showInputDialog(null,"Enter Last Name");
email=JOptionPane.showInputDialog(null,"Enter Your Email");
department=JOptionPane.showInputDialog(null,"Enter Department Name");
Salary=JOptionPane.showInputDialog(null,"Enter Salary Name");
**String insertion="insert into employees"
+ "(first_name, last_name, email, department ,salary )"+"values "
+ "(?,?,?,?,?)";**
**Ps=(PreparedStatement) MyCon.prepareStatement(insertion);
Ps.setString(1,Fname);
Ps.setString(2,Lname);
Ps.setString(3,email);
Ps.setString(4,department);
Ps.setString(5,Salary);
Ps.executeUpdate();**
}catch(Exception e)
{
e.printtrace();
}
You Should use this template:
PreparedStatement pstmt = con .prepareStatement ("INSERT INTO TableName (ColumnNmae1, ColumnNmae2, ColumnNmae3...) VALUES (?,?,?...);
pstmt.setType(1, value);
pstmt.setType(2, value);
pstmt.setType(3, value);
etc.
in the prepared statemnt you need to use exactly the same amount oof question mark as the columns you manchined in the statment.
for each question mark you shoukd setValue, you need to choose the right set for eac value typr, there is setString setInt etc...
In your specific case it should look like that:
PreparedStatement pstmt = con .prepareStatement ("INSERT INTO TableName (RegistrationNo,Date,SeniorPerson...) VALUES (?,?,?...);
pstmt.setString(1, regno);
pstmt.setDate(2, Date);
pstmt.setString(3, SeniorPerson);
etc.
Yours is an example of how to NOT use PreparedStatement.
Here's a better idea:
// Here's a PreparedStatement to satisfy the person who downvoted.
PreparedStatement stmt = connection.prepareStatement();
// I might have missed a '?' - you should check it.
String qry= "INSERT INTO Registration1(RegistrationNo,Date,SeniorPerson,NativePlace,Kul,Gotra,KulSwami,ResidensialAddress,PinCode,STDcode,TelephoneNo,MobileNo,Email,Website,Education,Branch,BirthDate,BloodGroup) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
// Bind the variables here
stmt.executeUpdate(qry);
You should go through this carefully.