Download Mysql-connector-java-5.1.31.jar add to Project BuildPath
Package Com.jdbc.test;import java.sql.drivermanager;import java.sql.resultset;import java.sql.SQLException; Import Java.sql.statement;import com.mysql.jdbc.Connection; Public classJdbcTest1 { Public StaticConnection getconnection () {Connection conn=NULL; Try{class.forname ("Com.mysql.jdbc.Driver"); Load Driver Conn= (Connection) drivermanager.getconnection ("Jdbc:mysql://localhost:3306/mydb?useunicode=true&characterencoding=utf-8&usessl=false","Root","123456"); Connect to Database}Catch(ClassNotFoundException |SQLException e) { //TODO auto-generated Catch blockE.printstacktrace (); } returnConn; } Public Static void Select() {Connection conn=getconnection (); String SQL="Select *from Book1"; Try{Statement St=conn.createstatement (); ResultSet RS=st.executequery (SQL); Execute SQL statement while(Rs.next ()) {System. out. Print (Rs.getstring ("Use_name")+" "); System. out. println (Rs.getint ("Use_age")+" "); } rs.close (); St.close (); Conn.close (); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } Public Static voidInsert () {Connection conn=getconnection (); String SQL="INSERT into Book1 values (' lixiaoming ', +)"; Try{Statement St=conn.createstatement (); intCount =st.executeupdate (SQL); System. out. println ("The table has been inserted into the"+count+"Bar Data"); St.close (); Conn.close (); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } Public Static voidDelete () {Connection conn=getconnection (); String SQL="Delete from Book1 where use_age ="; Try{Statement St=conn.createstatement (); intCount =st.executeupdate (SQL); System. out. println ("removed from the table"+count+"Bar Data"); St.close (); Conn.close (); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } Public Static voidUpdate () {Connection conn=getconnection (); String SQL="Update Book1 set use_age=30 where use_name = ' Zhangsan '"; Try{Statement St=conn.createstatement (); intCount =st.executeupdate (SQL); System. out. println ("updated from the table"+count+"Bar Data"); St.close (); Conn.close (); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } Public Static voidMain (string[] args) {//TODO auto-generated Method Stub Select();//Insert ();//Delete ();//update (); }}
Java JDBC Test