JDBC add, update, delete data
st.executeUpdate(sql) insert, update, delete operation
returns the number of affected records
Note: In the input sql statement, remember to add single quotes for the vachar type
The complete code is as follows:
public class JDBCTest { // establish a connection public static Connection getConnection(){ Connection conn=null; try { Class.forName("com.mysql.cj.jdbc.Driver").newInstance(); conn=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=FALSE&serverTimezone=UTC","root","xb199795"); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } // Insert data public static void insert() { String sql="insert into tbl_user(name,password,email)"+ "values('xiongda','123','[email protected]')"; Connection conn =getConnection(); try { Statement st=conn.createStatement(); int count =st.executeUpdate(sql); System.out.println( "Insert "+count+" records!" ); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // Update data public static void update() { String sql="update tbl_user set email='[email protected]' where name='xiongda'"; Connection conn =getConnection(); try { Statement st=conn.createStatement(); int count =st.executeUpdate(sql); System.out.println( "Updated "+count+" records!" ); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // delete data public static void delete() { String sql="delete from tbl_user where name='xiongda'"; Connection conn =getConnection(); try { Statement st=conn.createStatement(); int count =st.executeUpdate(sql); System.out.println( "Deleted "+count+" records!" ); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }