1. Download the interface package Mysql-connector-java-5.0.8-bin.jar
2. Programming
(1) Load driver
(2) Programming connection operation
(3) Return result processing
Programming examples
Import java.sql.*;p ublic class Access2database{public Connection getconn () {Connection conn=null;try{class.forname (" Com.mysql.jdbc.Driver "); String url= "Jdbc:mysql://localhost:3306/mytest"; String user= "root"; String password= "111"; conn=drivermanager.getconnection (url, user, password), if (conn!=null) {System.out.println (" The connection to database is successful! ");}} catch (Exception e) {e.printstacktrace ();} Return conn;} Public ResultSet getresultset (Statement stam,string sql) {ResultSet res=null;try {res=stam.executequery (SQL);} catch ( SQLException e) {e.printstacktrace ();} return res;} void Showresultset (ResultSet res) {}}
Import java.sql.*;p ublic class getconnection{public static void Main (string[] args) {access2database adb=new Access2database (); Connection Conn=adb.getconn (); Statement stam=null;try {Stam = Conn.createstatement ();} catch (SQLException E1) {e1.printstacktrace ();} Show Resultsetstring sql= "select * from student;"; ResultSet res=adb.getresultset (Stam, sql), try {System.out.println ("Name\tmajor\tscore"), while (Res.next ()) {String Name,major;int score;name=res.getstring (1); major=res.getstring (2); Score=res.getint (3); System.out.println (name+ "\ t" +major+ "\ T" +score);}} catch (SQLException e) {e.printstacktrace ();} Try{res.close ();} catch (SQLException e) {e.printstacktrace ();} Insert something into tablesql= "insert into student (Name,major,score) VALUES (' f ', ' Chinese ', ' 70 ');"; try {stam.execute (SQL);} catch (SQLException e) {e.printstacktrace ();} Delete something from the tablesql= "delete from student where name= ' f ';"; Try{stam.executeupdate (SQL);} catch (SQLException e) {e.printstacktrace ();} Change the DATA int the tablesql= "update student set score=100 where Name= ' a ' and major= ' Chinese '"; try{stam.executeupdate (sql);} catch (SQLException e) {e.printstacktrace ();} Prepared statementsql= "select * from student where name=?"; PreparedStatement pstam=null;try {pstam=conn.preparestatement (SQL);p stam.setstring (1, "a"); res=pstam.executequery (); System.out.println ("**********************"); while (Res.next ()) {String name,major;int score;name=res.getstring (1) ; major=res.getstring (2); Score=res.getint (3); System.out.println (name+ "\ t" +major+ "\ T" +score);}} catch (SQLException e) {e.printstacktrace ();} Release the resource of the Programtry{res.close ();p stam.close (); Stam.close (); Conn.close ();} catch (SQLException e) {e.printstacktrace ();}}}
Adjust the code as needed
Java methods for accessing MySQL database