First import Mysql-connector-java-5.1.10-bin.ja
:http://download.csdn.net/detail/u014112584/7359185
Mouse over the item, right-click to select Properties----->java Build Path------>add External JARS
Test code:
Import Java.sql.connection;import java.sql.drivermanager;import java.sql.resultset;import java.sql.SQLException; Import Com.mysql.jdbc.preparedstatement;import Com.mysql.jdbc.statement;public class Mysqltest {static String Drivername= "Com.mysql.jdbc.Driver"; static string Url= "Jdbc:mysql://localhost:3306/expression";//point to Data Source static string username= "root"; Static String password= ""; Static Java.sql.Statement Stmt=null; Static ResultSet Re=null; Static Connection Conn=null; Static PreparedStatement Pstm=null; /* * constructor is initialized */public mysqltest () {try{class.forname (drivername);//drive is loaded into the running environment, when loaded, the driver automatically to Drivermana GER Completed Registration System.out.println ("Create driver Success"); }catch (ClassNotFoundException e) {e.printstacktrace (); }/* * GET connection */public static Connection getconnection () {conn=null; try{conn= (Connection) drivermanager.getconnection (URL, username, password);//with Driver and connection address, you need to use DriverManager to get the connection SYSTEM.OUT.PRINTLN ("Connection database succeeded! "); }catch (SQLException e) {e.printstacktrace (); } return conn; /** * Close Connection * @param args */public static void free (ResultSet rs,connection Conn,java.sql.statement St MT2) {if (rs!=null) {try {rs.close ()},} catch (SQLException e) {//TODO auto-generated catch BlockSystem.out.println (" Shutdown resultset failed! "); E.printstacktrace ();} Finally{if (conn!=null) {try {conn.close ()} catch (SQLException e) {//TODO auto-generated catch BlockSystem.out.println ("Shutdown Connection failed!") "); E.printstacktrace ();} Finally{if (stmt2!=null) {try {stmt2.close ()} catch (SQLException e) {//TODO auto-generated catch block System.out.print ln ("Shutdown statement failed! "); E.printstacktrace ();}}}}}} public static void Main (String[]args) {mysqltest.getconnection (); try {stmt=conn.createstatement ();} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();} try {re=stmt.executequery ("SELECT * from Data"),} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacKtrace ();} int I=1;try {while (Re.next ()) {System.out.println (i++);}} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();} Free (RE,CONN,STMT); System.out.println ("OK"); }}
Java Access database more examples http://download.csdn.net/detail/u014112584/7359179