Tools: mysql-connector-java-5.1.40, Eclipse
1) First, to integrate the Mysql-connector-java package into Eclipse, right-click on the project and select Build path, this will happen, then OK!
2) Create a test class, test the connection, the code is as follows 1 import java.sql. 2 //connection This class is also available in Mysql-connector-java, but we run in a Java virtual machine, so we use the contents of the java.sql package.
1 ImportJava.sql.*;2 3 Public classmysqlconnection {4 Public Static voidMain (String args[]) {5 //1) Load MySQL drive6 Try {7Class.forName ("Com.mysql.jdbc.Driver");8System.out.println ("Success Loading driver!");9}Catch(Exception e) {Ten //Todo:handle Exception OneSystem.out.print ("Error Loading driver!"); A e.printstacktrace (); - } - //2) Establish a connection with MySQL the //getconnection three parameters, URL: Only connection protocol, connection host, and port number, as well as the database to connect; User: Connect to a database username; password: connection password - Try { -Connection Connection = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/world", "root", "538769"); -SYSTEM.OUT.PRINTLN ("Connect to world!"); + //3) Through connection, create statement -Statement stm =connection.createstatement (); + //4) Results after the query is stored in the ResultSet AResultSet RSet = Stm.executequery ("SELECT * from City"); at //the next method in ResultSet is to determine if the next is empty - while(Rset.next ()) { -System.out.println ("The City" + rset.getstring ("ID") + "is" + rset.getstring ("Name")); - //System.out.println (rset.getstring ("ID", "Name")); - - } in -}Catch(Exception e) { to //Todo:handle Exception +SYSTEM.OUT.PRINTLN ("Error Get data!"); - e.printstacktrace (); the } * $ }Panax Notoginseng}
3) The source code to run, you can see the results of the query.
One of JDBC's getting started-connecting MySQL Labs