I am using Java to insert some data into mysql . But having apostrophe(punctuation mark) into data (near's weekly tracker suggests that job growth) it gives me MySQLSyntaxErrorException.Please give me proper solution to handle that
Code I have isa
void insert(String a1,String a2, String a3) {
String nt = a2;
String pt = a3;
String tb = a1;
query = "insert into "+tb+"(head,des) values('"+nt+"','"+pt+"')";
try {
stmt.executeUpdate(query);
System.out.println("inserted"); //con.close();
} catch (SQLException ex) {
// Logger.getLogger(conec.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
Use query parameters, not string concatenation. This will allow the database driver to format the values you send to the database server, rather than re-inventing this wheel yourself.
String sql = "insert into ... values (?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, nt);
stmt.setString(2, pt);
stmt.executeUpdate();
query = "insert into "+tb+"(head,des) values('"+nt+"','"+pt+"')";
should be
query = "insert into "+tb+" (head, des) values ('"+nt+"','"+pt+"')";
Please do these changes and let me know if there are still problems....
Related
I am writing the code for a sign-up page for a system. Once the button is clicked, the system will check if the user is above the age of 14. If true, the system should save all the inputted data into a SQL Database.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int age = Integer.parseInt(Age_Input.getText());
String firstname = FirstName_Input.getText();
String surname = Surname_Input.getText();
String email = Email_Input.getText();
String userid = UserID_InputSignUp.getText();
char[] pass = Password_InputSignUp.getPassword();
if (age<14) {
JOptionPane.showMessageDialog(null,"Sorry, You need to be at least 14 years to use this software... ");
new Login_Page().setVisible(true);
this.setVisible(false);
} else {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connect = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/user_info", "root", "nerdswonka");
Statement stmt = connect.createStatement();
String query1 = "INSERT INTO user_info(user_id, password, firstname, lastname, emailid, age) VALUES('"+userid+"', "+Arrays.toString(pass)+", '"+firstname+"', '"+surname+"', '"+email+"', "+age+");";
stmt.executeUpdate(query1);
JOptionPane.showMessageDialog(null, "Account Creation succesful!");
stmt.close();
connect.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error in connecting to SQL Database");
}
new Login_Page().setVisible(true);
this.setVisible(false);
}
}
The code isn't updating anything into the database and is simply showing JOptionPane after an exception (error ) comes. What edits can be done to the code so that values get stored into SQL?
The immediate cause of the failure is probably that your INSERT statement contains the following string which is not being single quoted:
Arrays.toString(pass)
However, you should completely abandon your current approach and instead use a prepared statement:
String sql = "INSERT INTO user_info (user_id, password, firstname, lastname, emailid, age) " +
"VALUES (?, ?, ?, ?, ?, ?)";
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user_info", "root", "nerdswonka");
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, userid);
ps.setString(2, Arrays.toString(pass));
ps.setString(3, firstname);
ps.setString(4, surname);
ps.setString(5, email);
ps.setInt(6, age);
int row = ps.executeUpdate();
System.out.println(row); // rows inserted (should be 1)
}
catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
}
Prepared statements do many things, one of which is handling the messy details about how to properly escape your literal data in a SQL query. In this case, they free you from having to worry about placing single quotes around your interpolated Java strings. Statements also prevent bad things like SQL injection from happening.
You are not printing your exception in catch block. You can use e.printStackTrace(); to print exception first.
I get an sql error when trying to insert something into my DB.
I give a bunch of input to my method, convert that input into strings or sql time and want to store it.
public static void setCourseList(String courseDescription, String courseName, LocalTime courseStart, LocalTime courseEnd, LocalDate courseDate, DayOfWeek courseDay) {
Connection conn = null;
try {
// db parameters
// path to db relative to run time directory
String url = "jdbc:sqlite:Holiday.db";
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?,);";
conn = DriverManager.getConnection(url);
System.out.println("Connected");
Statement stmt = conn.createStatement();
PreparedStatement pstmt = conn.prepareStatement(sqlInsertCourse);
pstmt.setString(1, courseName);
String courseStartString = courseStart.toString();
pstmt.setString(2, courseStartString);
java.sql.Time courseEndTime = Time.valueOf(courseEnd);
pstmt.setTime(3, courseEndTime);
java.sql.Date courseDateDate = java.sql.Date.valueOf(courseDate);
pstmt.setDate(4, courseDateDate);
String courseDayString = courseDay.toString();
pstmt.setString(5, courseDayString);
pstmt.executeUpdate();
pstmt.close();
System.out.println("Connection to SQLite has been established.");
// create tables if they do not exists
stmt.execute(sqlInsertCourse);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
I would expect it to store the input in my db.
I do get an [SQLITE_ERROR] SQL error or missing database (near ")": syntax error) error instead.
Any help is appreciated.
I am new to sql.
Change
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?,);";
To
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?);"; //<<<<<<<<<< extra comma removed
As per the comment on the line the final comma after the last ? has been removed.
Same as what Mike has answered, you can change it to
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (""put values here"");";
If you are wondering why it doesn't throw you an error, it's because there is no syntax error in the java, there's an error in the SQL which only the database can throw, but you're computer can't recognize. Hope this answers your question.
I have this java method:
public boolean insertAuthor(String userid, String password){
try{
String query1 = "INSERT INTO user (id, firstName, lastName, belonging, country) VALUES(?,?,?,?,?)";
PreparedStatement stmt = this.dbConn.prepareStatement(query1);
stmt.setInt(1,0);
stmt.setString(2,"default"); //Yes, it's correct with "default"
stmt.setString(3,"default");
stmt.setString(4,"default");
stmt.setString(5,"default");
//stmt.executeUpdate();
stmt.executeUpdate(query1, PreparedStatement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
int key=0;
if ( rs.next() ) {
key = rs.getInt(1);
}
String query2 = "INSERT INTO authentication (id, address, password, user_id, login_id) VALUES(?,?,?,?,?)";
stmt = this.dbConn.prepareStatement(query2);
stmt.setInt(1,0);
stmt.setString(2,"default");
stmt.setString(2,password);
stmt.setInt(2,key);
stmt.setString(2,userid);
stmt.executeUpdate();
return true;
}catch(Exception e){
System.err.println(e.getMessage());
}
return false;
}
Let me explain: I would like to execute two queries and the second one need the key that is generated in the first query (I need the primary key of the table "user" because user-authentication is a 1:1 relationship).
So:
Is this the correct way to execute more than one query?
Am I missing something with the returning key? Because if I run ONLY executeUpdate() and I comment every row below it the method works fine, but when I run the code in the example (with the first executeUpdate() commented) I get false (only false, no exception). Do I have to check something in my database?
Thanks in advance.
EDIT:
I found a solution. It was an error in columns and not in the method for getting the generated key itself. I will choose Joop Eggen's answer for the improvements that he showed me. Thanks!
There were a couple of improvements needed.
String query1 = "INSERT INTO user (firstName, lastName, belonging, country)"
+ " VALUES(?,?,?,?)";
String query2 = "INSERT INTO authentication (address, password, user_id, login_id)"
+ " VALUES(?,?,?,?)";
try (PreparedStatement stmt1 = this.dbConn.prepareStatement(query1,
PreparedStatement.RETURN_GENERATED_KEYS);
stmt2 = this.dbConn.prepareStatement(query2)) {
stmt1.setString(1, "default");
stmt1.setString(2, "default");
stmt1.setString(3, "default");
stmt1.setString(4, "default");
stmt1.executeUpdate();
try (ResultSet rs = stmt1.getGeneratedKeys()) {
if (rs.next()) {
int userid = rs.getInt(1);
stmt2.setString(1, "default");
stmt2.setString(2, password);
stmt2.setInt(3, key);
stmt2.setString(4, userid);
stmt2.executeUpdate();
return true;
}
}
} catch (SQLException e) {
System.err.println(e.getMessage());
}
return false;
Try-with-resources close automatically, also on exception and return.
You have two prepared statements to close.
The executeUpdate with the SQL is for the parents class Statement, and does disrespect the parameter settings. You chose that for the generated keys parameter, but that goes into Connection.prepareStatement.
(SQL) The generated keys should not be listed/quasi-inserted.
It is debatable whether one should catch the SQLException here. throws SQLException is what works for me.
I'll advise you have a username field in your user table so after inserting you can simply do a Select id from user Where username...
Is there a way to retrieve the auto generated key from a DB query when using a java query with prepared statements.
For example, I know AutoGeneratedKeys can work as follows.
stmt = conn.createStatement();
stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
if(returnLastInsertId) {
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
However. What if I want to do an insert with a prepared Statement.
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql);
//this is an error
stmt.executeUpdate(Statement.RETURN_GENERATED_KEYS);
if(returnLastInsertId) {
//this is an error since the above is an error
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
Is there a way to do this that I don't know about. It seems from the javadoc that PreparedStatements can't return the Auto Generated ID.
Yes. See here. Section 7.1.9. Change your code to:
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.executeUpdate();
if(returnLastInsertId) {
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
There's a couple of ways, and it seems different jdbc drivers handles things a bit different, or not at all in some cases(some will only give you autogenerated primary keys, not other columns) but the basic forms are
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
Or use this form:
String autogenColumns[] = {"column1","column2"};
stmt = conn.prepareStatement(sql, autogenColumns)
Yes, There is a way. I just found this hiding in the java doc.
They way is to pass the AutoGeneratedKeys id as follows
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
I'm one of those that surfed through a few threads looking for solution of this issue ... and finally get it to work. FOR THOSE USING jdbc:oracle:thin: with ojdbc6.jar PLEASE TAKE NOTE:
You can use either methods:
(Method 1)
Try{
String yourSQL="insert into Table1(Id,Col2,Col3) values(SEQ.nextval,?,?)";
myPrepStatement = <Connection>.prepareStatement(yourSQL, Statement.RETURN_GENERATED_KEYS);
myPrepStatement.setInt(1, 123);
myPrepStatement.setInt(2, 123);
myPrepStatement.executeUpdate();
ResultSet rs = getGeneratedKeys;
if(rs.next()) {
java.sql.RowId rid=rs.getRowId(1);
//what you get is only a RowId ref, try make use of it anyway U could think of
System.out.println(rid);
}
} catch (SQLException e) {
//
}
(Method 2)
Try{
String yourSQL="insert into Table1(Id,Col2,Col3) values(SEQ.nextval,?,?)";
//IMPORTANT: here's where other threads don tell U, you need to list ALL cols
//mentioned in your query in the array
myPrepStatement = <Connection>.prepareStatement(yourSQL, new String[]{"Id","Col2","Col3"});
myPrepStatement.setInt(1, 123);
myPrepStatement.setInt(2, 123);
myPrepStatement.executeUpdate();
ResultSet rs = getGeneratedKeys;
if(rs.next()) {
//In this exp, the autoKey val is in 1st col
int id=rs.getLong(1);
//now this's a real value of col Id
System.out.println(id);
}
} catch (SQLException e) {
//
}
Basically, try not used Method1 if you just want the value of SEQ.Nextval, b'cse it just return the RowID ref that you may cracked your head finding way to make use of it, which also don fit all data type you tried casting it to! This may works fine (return actual val) in MySQL, DB2 but not in Oracle.
AND, turn off your SQL Developer, Toad or any client which use the same login session to do INSERT when you're debugging. It MAY not affect you every time (debugging call) ... until you find your apps freeze without exception for some time. Yes ... halt without exception!
Connection connection=null;
int generatedkey=0;
PreparedStatement pstmt=connection.prepareStatement("Your insert query");
ResultSet rs=pstmt.getGeneratedKeys();
if (rs.next()) {
generatedkey=rs.getInt(1);
System.out.println("Auto Generated Primary Key " + generatedkey);
}
I tried to save / edit / delete a new row in the database. writing in the gui values to be saved with getText ()
here is the code
Connection conn = Connessione.ConnecrDb();
Statement stmt = null;
ResultSet emps = null;
try{
String sql;
sql = "INSERT INTO PROGETTO.LIBRO (ISBN, DISPONIBILITA, TITOLO, CASA_EDITRICE, CODICE_AUTORE, GENERE, PREZZO)"
+ "VALUES (txt_isbn, txt_disp, txt_titolo, txt_casa, txt_autore, txt_genere, txt_prezzo)";
stmt = conn.createStatement();
emps = stmt.executeQuery(sql);
String ISBN= txt_isbn.getText();
String DISPONIBILITA= txt_disp.getText();
String TITOLO= txt_titolo.getText();
String CASA_EDITRICE= txt_casa.getText();
String CODICE_AUTORE= txt_autore.getText();
String GENERE= txt_genere.getText();
String PREZZO = txt_prezzo.getText();
JOptionPane.showMessageDialog(null, "SALVATO");
}catch(SQLException | HeadlessException e)
{
JOptionPane.showMessageDialog(null, e);
}
finally
{
try{
if (emps != null)
emps.close();
}
catch (SQLException e) { }
try
{
if (stmt != null)
stmt.close();
}
catch (SQLException e) { }
}
Getting this error: column not allowed here
Above code just takes care of insert operation. How can I delete and modify table record?
You have asked 2 different questions here
1. Column not allowed here
This happened because you have not passed values for any of parameter into insert statement.
I am not sure about your requirement however I will use PreparedStatement for this scenario.
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, "MindPeace");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
preparedStatement .executeUpdate();
2. This code is only to save the data, delete, and modify an entire row how can I do?
Answer is very simple. You have to write code for the same :)
You need 3 SQL statement which has DELETE and UPDATE operation just like insert in above example.
String sql = "INSERT INTO PROGETTO.LIBRO (ISBN, DISPONIBILITA, TITOLO, "
+ "CASA_EDITRICE, CODICE_AUTORE, GENERE, PREZZO)"
+ "VALUES (?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement stmt = conn.createStatement()) {
NumberFormat numberFormat = NumberFormat.getInstance(Locale.ITALY);
String ISBN = txt_isbn.getText();
String DISPONIBILITA = txt_disp.getText();
String TITOLO = txt_titolo.getText();
String CASA_EDITRICE = txt_casa.getText();
String CODICE_AUTORE = txt_autore.getText();
String GENERE = txt_genere.getText();
BigDecimal PREZZO = new BigDecimal(
numberFormat.parse(txt_prezzo.getText()).doubleValue())
.setScale(2);
stmt.setString(1, ISBN);
stmt.setString(2, DISPONIBILITA);
stmt.setString(3, TITOLO);
stmt.setString(4, CASA_EDITRICE);
stmt.setString(5, CODICE_AUTORE);
stmt.setString(6, GENERE);
stmt.setBigDecimal(7, PREZZO);
int updateCount = stmt.executeUpdate();
JOptionPane.showMessageDialog(null, "SALVATO");
} catch(SQLException | HeadlessException e) {
JOptionPane.showMessageDialog(null, e);
}
Try-with-resources closes the stmt automatically.
The prepared statement replaces the value in the SQL with something like:
INSERT INTO table(column1, colum2, ....)
VALUES('De\'l Rey',
1234.50,
...)
for:
"De'l Rey"
1.234,50
updateCount should be 1 on success.
Wooow..true!!
I created three buttons to delete / update / insert and now it all works and automatically updates the tables.
you've been very very great. Thank you very much.
one last thing.
if I wanted to insert an error message when I delete / update etc "book not found" I tried to create an if:
Boolean found = false;
try{
sql= delete......
etc
if (!found)
JOptionPane.showMessageDialog(null, "NOT FOUND","ERRORE",JOptionPane.WARNING_MESSAGE);
etc...
Connection conn = Connessione.ConnecrDb();
Statement stmt = null;
ResultSet emps = null;
try{
String sql= "DELETE FROM progetto.libro WHERE isbn =?"; /
pst=(OraclePreparedStatement) conn.prepareStatement(sql);
pst.setString (1, txt_isbn.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "ELIMINATO");
Update_table();
txt_isbn.setText("");
txt_disp.setText("");
txt_titolo.setText("");
txt_casa.setText("");
txt_autore.setText("");
txt_genere.setText("");
txt_prezzo.setText("");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
if you find the book must exit the book removed, or "not found". but as I deployed I always come out "deleted". why?
thanks again