JDBC-database update Operation Programming (3)
First, create a static method. The Code is as follows:
public static Statement getStatement(){ Statement st = null; try { Class.forName("com.mysql.jdbc.Driver"); Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_dbb", "root", ""); st = (Statement) conn.createStatement(); } catch (Exception e) { // TODO: handle exception } return st; }
This static class obtains the Statement and uses the Statement class to implement addition, update, and deletion operations, respectively implemented by static code. The Code is as follows:
Public static Statement getStatement () {Statement st = null; try {Class. forName ("com. mysql. jdbc. driver "); Connection conn = (Connection) DriverManager. getConnection ("jdbc: mysql: // localhost: 3306/jsp_dbb", "root", ""); st = (Statement) conn. createStatement ();} catch (Exception e) {// TODO: handle exception} return st;} public static void insert () {try {String SQL = "INSERT INTO tbl_user (name, password, email)" + "VALUES ('Tom ', '123', 'Tom @ qq.com ')"; statement st = getStatement (); int count = st.exe cuteUpdate (SQL); System. out. println ("inserted" + count + "row data");} catch (Exception e) {// TODO: handle exception} public static void update () {try {String SQL = "UPDATE tbl_user SET email = 'Tom @ 136.com 'WHERE name = 'Tom'"; Statement st = getStatement (); int count = st.exe cuteUpdate (SQL); System. out. println ("updated" + count + "row data");} catch (Exception e) {// TODO: handle exception} public static void delete () {try {String SQL = "delete from tbl_user WHERE name = 'Tom '"; Statement st = getStatement (); int count = st.exe cuteUpdate (SQL); System. out. println ("deleted" + count + "row data");} catch (Exception e) {//} public static void main (String [] args) {// insert (); // update (); delete ();}