mysql-connector-java-5.1.46.zip【解压后里面jar文件就是所需要的】
https://dev.mysql.com/get/Downloads/Connector-J/mysql-connector-java-5.1.46.zip
jdbc连接例子
有时候还是不行,然后尝试把mysql的驱动复制到Tomcat的lib文件夹里面就可以了
代码
1 package com.test; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 import java.sql.Statement; 7 8 public class Test1 { 9 10 public static void main(String[] args) throws Exception { 11 //1、加载驱动 12 Class.forName("com.mysql.jdbc.Driver"); 13 //2、连接mysql的指定数据库 14 Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/liwei", "root", "123456"); 15 //3、通过数据库的连接操作数据库,实现增删改查 16 Statement cs = con.createStatement(); 17 //4、实现sql,然后返回查询结果 18 ResultSet rs = cs.executeQuery("select * from user"); 19 //处理返回结果, 20 while(rs.next()) { 21 System.out.println(rs.getString(1)); 22 System.out.println(rs.getString(2)); 23 System.out.println(rs.getString(3)); 24 } 25 //关闭资源连接 26 rs.close(); 27 cs.close(); 28 con.close(); 29 } 30 31 }
用配置文件来加载
1 package com.test; 2 3 import java.io.FileInputStream; 4 import java.io.InputStream; 5 import java.sql.Connection; 6 import java.sql.DriverManager; 7 import java.sql.ResultSet; 8 import java.sql.Statement; 9 import java.util.Properties; 10 11 public class Test1 { 12 13 public static void main(String[] args) throws Exception { 14 Properties pt = new Properties(); 15 FileInputStream fis = new FileInputStream("dbinfo.properties"); 16 pt.load(fis); 17 String driver = pt.getProperty("driver"); 18 String uri = pt.getProperty("uri"); 19 String userName = pt.getProperty("userName"); 20 String password = pt.getProperty("password"); 21 //1、加载驱动 22 Class.forName(driver); 23 //2、连接mysql的指定数据库 24 Connection con = DriverManager.getConnection(uri, userName, password); 25 //3、通过数据库的连接操作数据库,实现增删改查 26 Statement cs = con.createStatement(); 27 //4、实现sql,然后返回查询结果 28 ResultSet rs = cs.executeQuery("select * from user"); 29 //处理返回结果, 30 while(rs.next()) { 31 System.out.println(rs.getString(1)); 32 System.out.println(rs.getString(2)); 33 System.out.println(rs.getString(3)); 34 } 35 //关闭资源连接 36 fis.close(); 37 rs.close(); 38 cs.close(); 39 con.close(); 40 } 41 42 }