//-----------------------------------Select----------------------------------Importjava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement; Public classtestselect{ Public Static voidMain (string[] args) {Connection conn=NULL; Statement stmt=NULL; ResultSet RS=NULL; Try{class.forname ("Com.mysql.jdbc.Driver"); Conn=DriverManager. getconnection ("Jdbc:mysql://localhost/mydata?user=root&password=root"); stmt=conn.createstatement (); String SQL= "SELECT * FROM article"; RS=stmt.executequery (SQL); while(Rs.next ()) {System.out.println (Rs.getint ("id")); System.out.println (Rs.getstring ("Title")); } } Catch(Exception e) {e.printstacktrace (); } finally { Try { if(rs! =NULL) {rs.close (); RS=NULL; } if(stmt! =NULL) {stmt.close (); stmt=NULL; } if(Conn! =NULL) {conn.close (); Conn=NULL; } } Catch(SQLException e) {e.printstacktrace (); } } }}//-------------------------Insert--------------------------ImportJava.sql.*; Public classTestinsert { Public Static voidMain (string[] args) {Connection conn=NULL; Statement stmt=NULL; Try{class.forname ("Com.mysql.jdbc.Driver"); Conn=DriverManager. getconnection ("Jdbc:mysql://localhost/mydata?user=root&password=root"); stmt=conn.createstatement (); String SQL= "INSERT into article (title) VALUES (' FFF ')"; Stmt.executeupdate (SQL); } Catch(Exception e) {e.printstacktrace (); } finally { Try{stmt.close (); Conn.close (); } Catch(SQLException e) {e.printstacktrace (); } } }}//-----------------------------Update----------------------------ImportJava.sql.*; Public classTestupdate { Public Static voidMain (String[]args) {Connection conn=NULL; Statement stmt=NULL; Try{class.forname ("Com.mysql.jdbc.Driver"); Conn= Drivermanager.getconnection ("Jdbc:mysql://localhost/mydata?user=root&password=root"); stmt=conn.createstatement (); String SQL= "Update Article set title = ' GGG ' where id=5"; Stmt.executeupdate (SQL); }Catch(Exception e) {e.printstacktrace (); }finally{ Try{stmt.close (); Conn.close (); } Catch(SQLException e) {e.printstacktrace (); } } }}//---------------------------Delete-------------------------ImportJava.sql.*; Public classTestdelete { Public Static voidMain (String[]args) {Connection conn=NULL; Statement stmt=NULL; Try{class.forname ("Com.mysql.jdbc.Driver"); Conn= Drivermanager.getconnection ("Jdbc:mysql://localhost/mydata?user=root&password=root"); stmt=conn.createstatement (); Stmt.execute ("Delete from article where title= ' FFF '"); }Catch(Exception e) {e.printstacktrace (); }finally{ Try{conn.close (); Stmt.close (); } Catch(SQLException e) {e.printstacktrace (); } } }}
Java JDBC----Select, INSERT, UPDATE, delete for MySQL