Download MySQL database: http://dev.mysql.com/downloads/mysql/, unzip to local
Download jar package: http://dev.mysql.com/downloads/connector/j/, download zip archive package
Create a database and insert several data:
Create TableMyDB; UseMyDB;Create TableStudent (namevarchar(8), noChar(7));Insert intoStudentValues('Zhang','011');Insert intoStudentValues('Li','021');Select * fromStudent
Database Connection class:
PackageG.dao;Importjava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement; Public classDbConnection { Public StaticConnection getconnection ()throwsClassNotFoundException, SQLException {class.forname ("Com.mysql.jdbc.Driver"); String URL= "Jdbc:mysql://127.0.0.1:3306/mydb"; Connection Connection= Drivermanager.getconnection (URL, "root", "root"); returnconnection; } Public Static voidFree (Connection Connection, Statement Statement, ResultSet ResultSet) {Try { if(ResultSet! =NULL) {resultset.close (); } if(Statement! =NULL) {statement.close (); } if(Connection! =NULL) {connection.close (); } } Catch(SQLException e) {e.printstacktrace (); } }}
To test the JDBC connection:
PackageG.dao;Importjava.sql.Connection;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSet;Importjava.sql.SQLException; Public classTESTJDBC { Public Static voidMain (string[] args) {Connection Connection=NULL; PreparedStatement Statement=NULL; ResultSet ResultSet=NULL; Try{Connection=dbconnection.getconnection (); String SQL= "SELECT * FROM Student"; Statement=connection.preparestatement (SQL); ResultSet=Statement.executequery (); while(Resultset.next ()) {System.out.println (resultset.getstring ("Name") + ":" + resultset.getstring ("no"))); } } Catch(ClassNotFoundException e) {e.printstacktrace (); } Catch(SQLException e) {e.printstacktrace (); } }}