I’m new to JDBC and using the following code to update the row using MySQL JDBC driver. I have no idea why executeUpdate() is not updating the content in the database.
import java.sql.*; import java.util.*; public class UpdateDb { UpdateDb() throws Exception,SQLException{ Scanner sc = new Scanner(System.in); Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedb","root",""); String q="update table inserttbl set Name=?, City=? where id=?"; System.out.print("Enter new name to update: "); String n = sc.nextLine(); System.out.print("Enter new city name to update: "); String c = sc.nextLine(); System.out.print("Enter previous id: "); int id = sc.nextInt(); PreparedStatement ps = conn.prepareStatement(q); ps.setString(1, n); ps.setString(2, c); ps.setInt(3, id); ps.executeUpdate(); System.out.print("updated"); conn.close(); } public static void main(String[] arg) { try { UpdateDb up = new UpdateDb(); } catch(Exception e) { e.getStackTrace(); } } }
Can anyone help me?
Advertisement
Answer
Your query string is wrong. It should be something like this:
String updateQuery = "UPDATE inserttbl SET Name=?, City=? WHERE id=?";
Look here for the proper syntax of update: https://www.mysqltutorial.org/mysql-jdbc-update
Also if you want to update then use an update table command. The command that you used for insert is wrong.
Also for error print out the exception that you logged.