1.首先,导入驱动mysql-connector-java-5.1.6-bin.jar。2.创建数据库链接类DBConnection:public class DBConnection { private static final String DRIVER_CLASS="com.mysql.jdbc.Driver"; private static final String DATABASE_URL="jdbc:mysql://localhost:3306/数据库名?user=root&password=sa&useUnicode=true&characterEncoding=GB2312"; public static Connection getConnection(){ Connection con = null ; try { Class.forName(DRIVER_CLASS); con = DriverManager.getConnection(DATABASE_URL); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return con; } public static void closeResultSet(ResultSet rs){ if(rs != null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void closeStatement(Statement stmt){ if(stmt != null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void closePreparedStatement(PreparedStatement pstmt){ if(pstmt != null){ try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void closeConnection(Connection con){ if(con != null){ try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } } 3.创建测试类TestMySqlJDBC: public class TestMySqlJDBC { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Connection con = DBConnection.getConnection(); if(con==null){ System.out.println("con is null "); }else{ System.out.println("con is not null"); } try { Statement stmt = con.createStatement(); String sql = "select * from student"; ResultSet rs = stmt.executeQuery(sql); while(rs.next()){ System.out.println(rs.getString("stuName")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }