当前位置:   article > 正文

JDBC连接mysql

jdbc连接mysql

1、数据库驱动

驱动:声卡、显卡、数据库。

驱动由数据库厂商提供。

程序会通过数据库驱动和数据库交互。

2、JDBC

SUN公司为了简化开发人员的操作(对数据库的统一),提供了一个(java操作数据库的)规范,俗称JDBC。规范的实现由厂商去做。对于开发人员,我们只需要会JDBC即可。

除了java自带的java.sql和javaxsql两个包外,还需要导入mysql-connector-java-5.1.47.jar包

下载地址:MySQL :: Download MySQL Connector/J (Archived Versions)

3、第一个JDBC程序

3.1、创建测试库数据库

  1. CREATE DATABASE jdbcStudy CHARACTER SET utf8 COLLATE utf8_general_ci;
  2. USE jdbcStudy;
  3. CREATE TABLE users (
  4. id INT ,
  5. `name` VARCHAR(40),
  6. `password` VARCHAR(40),
  7. `email` VARCHAR(60),
  8. birthday DATE,
  9. PRIMARY KEY (`id`)
  10. )
  11. INSERT INTO users (`id`,`name`,`password`,`email`,`birthday`)VALUE(1,'zhangsan','123456','zs@sina.com','1980-02-21'),
  12. (2,'lisi','123456','lisi@sina.com','1980-08-01'),(3,'wangmazi','123456','wangmazi@sina.com','1980-12-12'),(4,'hehe','123456','hehe@sina.com','1980-04-22');

3.2、导入数据库驱动

在项目下建一个lib目录,将jar包粘贴到目录下,然后右键lib目录,选择add as library才算导入。

3.3、编写测试代码

  1. public class JdbcTest01 {
  2. public static void main(String[] args) throws SQLException, ClassNotFoundException {
  3. new JdbcTest01().m1();
  4. }
  5. public void m1() throws ClassNotFoundException, SQLException {
  6. //1.加载驱动
  7. Class.forName("com.mysql.jdbc.Driver"); //固定写法 背
  8. //2.用户信息和url
  9. //?userUnicode=true&characterEncoding=utf8&useSSL=true 分别是支持中文编码,设定中文字符集,ssl使用安全的连接
  10. //ssl这里之所以设置false是因为SQL版本大于connect版本,就要设置成false
  11. String url ="jdbc:mysql://localhost:3306/jdbcstudy?userUnicode=true&characterEncoding=utf8&useSSL=false"; //固定写法 背
  12. String username = "root";
  13. String password = "123456";
  14. //3.连接成功,返回一个数据库对象
  15. //connection这个对象就代表数据库(jdbcstudy)
  16. Connection connection = DriverManager.getConnection(url,username,password);
  17. //4.执行sql的对象
  18. //通过connection对象的createStatement方法创建一个Statement类型的对象
  19. Statement statement = connection.createStatement();
  20. //5.执行sql的对象去执行sql,可能存在结果,查看返回结果。
  21. //通过statement对象的executeQuery方法传入sql执行,返回ResultSet类型的结果集。
  22. String sql="SELECT * FROM users;";
  23. ResultSet resultSet = statement.executeQuery(sql);//这个结果集封装了我们全部的查询结果
  24. while(resultSet.next()){
  25. System.out.println(resultSet.getObject("id"));
  26. System.out.println(resultSet.getObject("name"));
  27. System.out.println(resultSet.getObject("password"));
  28. System.out.println(resultSet.getObject("email"));
  29. System.out.println(resultSet.getObject("birthday"));
  30. }
  31. //6.释放连接
  32. //倒着释放资源,最后用的先释放
  33. resultSet.close();
  34. statement.close();
  35. connection.close();
  36. }
  37. }
  • DriverManager:
  1. // 原来的写法:DriverManager.registerDriver(new com.mysql.jdbc.Driver);
  2. // 为什么用Class.forName加载,因为用Class.forName加载实际上就是去加载Driver类的静态代码块,里面就是上面的那个写法,如果用原来的写法,就相当注册(registerDriver)了两次驱动。
  3. Class.forName("com.mysql.jdbc.Driver"); //固定写法 加载驱动

Driver源码:

  • URL
  1. String url ="jdbc:mysql://localhost:3306/jdbcstudy?userUnicode=true&characterEncoding=utf8&useSSL=false";
  2. //mysql默认端口号3306
  3. //jdbc:mysql://主机地址:端口号/数据库名?参数1&参数2&参数3
  4. //oracle默认端口号1521
  5. //jdbc:oracle:thin:@localhost:1521:sid

ssl这里之所以设置false是因为SQL版本大于connect版本,就要设置成false,问题详见:解决Exception in thread “main“ com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications-CSDN博客

  • DriverManager
  1. Connection connection = DriverManager.getConnection(url,username,password);//连接数据库,返回一个数据库对象
  2. //connection代表数据库
  3. //这个对象可以做:
  4. //数据库设置自动提交 connection.setAutoCommit()
  5. //事务提交 connection.commit()
  6. //事务回滚 connection.rollback()
  • Statement(执行sql对象 )

PrepareStatement也是执行sql对象但与前者有区别,后面会说到

  1. Statement statement = connection.createStatement();//创建一个执行sql对象 Statement
  2. String sql="SELECT * FROM users;";//编写sql
  3. statement.execute(sql);//执行所有sql
  4. statement.executeQuery(sql);//执行查询sql,返回一个结果集ResultSet
  5. statement.executeUpdate(sql);//执行更新,插入,删除sql都用这个,返回一个受影响的行数
  6. statement.executeBatch();//执行批处理sql,多条sql一块
  7. //
  • ResultSet(查询sql的结果集:封装了所有的查询结果)
  1. resultSet.getObject(sql);//在不知道列类型的情况下使用
  2. //如果知道类型就用指定的类型
  3. resultSet.getString(sql);
  4. resultSet.getInt(sql);
  5. resultSet.getFloat(sql);
  6. resultSet.getDouble(sql);
  7. resultSet.getDate(sql);

遍历相关:

  1. resultSet.next();//下移,并返回当前结果
  2. resultSet.beforeFirst();//移动到最前面
  3. resultSet.afterLast();//移动到最后面
  4. resultSet.previous();//移动到前一行
  5. resultSet.absolute(row);//移动到指定行
  • 释放资源(必须做)
  1. resultSet.close();
  2. statement.close();
  3. connection.close();

4、statement对象

Jdbc中的statement对象用于向数据库发送SQL语句,想完成对数据库的增删改查,只需要通过这个对象向数据库发送增删改查语句即可。

Statement对象的executeUpdate方法,用于向数据库发送增、删、改的sq|语句, executeUpdate执行完后, 将会返回一个整数(即增删改语句导致了数据库几行数据发生了变化)。

Statement.executeQuery方法用于向数据库发生查询语句,executeQuery方法返回代表查询结果的ResultSet对象。

CRUD操作-create

使用executeUpdate(String sql)方法完成数据添加操作,示例操作:

  1. Statement statement = connection.createStatement();
  2. String sql = "insert into user(...) values(...)";
  3. int num = statement.executeUpdate(sql);
  4. if(num>0){
  5. System.out.println("插入成功");
  6. }

CRUD操作-delete

使用executeUpdate(String sql)方法完成数据删除操作,示例操作:

  1. Statement statement = connection.createStatement();
  2. String sql = "delete from user where id =1";
  3. int num = statement.executeUpdate(sql);
  4. if(num>0){
  5. System.out.println("删除成功");
  6. }

CURD操作-read

使用executeUpdate(String sql)方法完成数据查询操作,示例操作:

  1. Statement statement = connection.createStatement();
  2. String sql = "select * from user where id =1";
  3. ResultSet rs= statement.executeQuery(sql);
  4. if(rs.next()){
  5. System.out.println("");
  6. }

5、提取工具类

  • 为什么要提取工具类:

    因为jdbc从开始连接数据库到最后释放,变的只有中间sql的执行操作,所以将加载驱动,连接数据库等操作提出来可以节省代码。

5.1、具体操作:

  1. 创建一个utils工具包,用于存放项目所有工具类。

  2. 在utils工具包下面创建JdbcUtils工具类

    1. public class JdbcUtils {
    2. private static String driver;
    3. private static String url;
    4. private static String username;
    5. private static String password;
    6. static {
    7. try {
    8. InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
    9. Properties properties = new Properties();
    10. properties.load(in);
    11. driver = properties.getProperty("driver");
    12. url = properties.getProperty("url");
    13. username = properties.getProperty("username");
    14. password = properties.getProperty("password");
    15. //1.驱动只用加载一次,所以放在static下
    16. Class.forName(driver);
    17. } catch (IOException | ClassNotFoundException e) {
    18. e.printStackTrace();
    19. }
    20. }
    21. //2.获取连接
    22. public static Connection getConnection() throws SQLException {
    23. return DriverManager.getConnection(url,username,password);
    24. }
    25. //3.释放资源 注意顺序
    26. public static void release(Connection conn, Statement statement, ResultSet resultSet) {
    27. if (resultSet!=null){
    28. try {
    29. resultSet.close();
    30. } catch (SQLException throwables) {
    31. throwables.printStackTrace();
    32. }
    33. }
    34. if (statement!=null){
    35. try {
    36. statement.close();
    37. } catch (SQLException throwables) {
    38. throwables.printStackTrace();
    39. }
    40. }
    41. if (conn!=null){
    42. try {
    43. conn.close();
    44. } catch (SQLException throwables) {
    45. throwables.printStackTrace();
    46. }
    47. }
    48. }
    49. }
  3. 提取配置信息

    在这个例子中,为了低耦合,我们也需要将操作数据库的信息提出来到配置信息中方便以后随时更改。

    在src目录下创建file为db.properties将数据库相关配置信息保存。

    1. driver=com.mysql.jdbc.Driver
    2. url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false
    3. username=root
    4. password=123456

5.2、编写增删改查类

在上面我们已经将数据库工具类提取出来,下面我们可以增删改查类也写出来。

  1. public class TestInsert {
  2. public static void main(String[] args) {
  3. Connection conn= null;
  4. Statement sta= null;
  5. ResultSet res= null;
  6. try {
  7. conn = JdbcUtils.getConnection();//获取连接
  8. sta = conn.createStatement();//获得sql的执行对象
  9. String sql = "insert into users(id,`name`,password,email,birthday)value(6,'wangshaonan','123456','hvri1@qq.com','2000.12.21')";
  10. int i = sta.executeUpdate(sql);
  11. if (i>0){
  12. System.out.println("插入成功");
  13. }
  14. } catch (SQLException throwables) {
  15. throwables.printStackTrace();
  16. }finally {
  17. JdbcUtils.release(conn,sta,null);
  18. }
  19. }
  20. }
  1. public class TestDelete {
  2. public static void main(String[] args) {
  3. Connection conn =null;
  4. Statement sta = null;
  5. try {
  6. conn = JdbcUtils.getConnection();//连接数据库
  7. sta = conn.createStatement();
  8. String sql = "DELETE FROM users WHERE id = 5";
  9. int i = sta.executeUpdate(sql);
  10. if (i>0){
  11. System.out.println("删除成功");
  12. }
  13. } catch (SQLException throwables) {
  14. throwables.printStackTrace();
  15. }finally {
  16. JdbcUtils.release(conn,sta,null);
  17. }
  18. }
  19. }
  1. public class TestUpdate {
  2. public static void main(String[] args) {
  3. Connection conn=null;
  4. Statement sta=null;
  5. try {
  6. conn = JdbcUtils.getConnection();
  7. sta = conn.createStatement();
  8. String sql = "UPDATE `users` SET `name` = 'zhangzhitao' WHERE id =3";
  9. int i = sta.executeUpdate(sql);
  10. if(i>0){
  11. System.out.println("修改成功");
  12. }
  13. } catch (SQLException throwables) {
  14. throwables.printStackTrace();
  15. }finally {
  16. JdbcUtils.release(conn,sta,null);
  17. }
  18. }
  19. }
  1. public class TestSelect {
  2. public static void main(String[] args) {
  3. Connection conn = null;
  4. Statement sta = null;
  5. ResultSet res = null;
  6. try {
  7. conn = JdbcUtils.getConnection();
  8. sta = conn.createStatement();
  9. String sql ="SELECT * FROM `users`";
  10. res = sta.executeQuery(sql);
  11. while (res.next()){
  12. System.out.println(res.getInt("id"));
  13. System.out.println(res.getString("name"));
  14. System.out.println(res.getString("password"));
  15. System.out.println(res.getString("email"));
  16. System.out.println(res.getString("birthday"));
  17. }
  18. } catch (SQLException throwables) {
  19. throwables.printStackTrace();
  20. }finally {
  21. JdbcUtils.release(conn,sta,res);
  22. }
  23. }
  24. }

7、SQL注入的问题

sql注入问题本质就是字符串的拼接。

  1. public class TestSQL注入问题 {
  2. public static void main(String[] args) {
  3. //m1("lisi","123456")正常登录
  4. //传入'or' 1=1
  5. // 让sql语句变为SELECT * FROM `users` WHERE `name` = '' OR 1=1 AND `password` = '123456'即可注入获取全部的用户名和密码
  6. m1(" 'or' 1=1","123456");//sql注入
  7. }
  8. public static void m1 (String username,String password){
  9. Connection conn = null;
  10. Statement sta = null;
  11. ResultSet res = null;
  12. try {
  13. conn = JdbcUtils.getConnection();
  14. sta = conn.createStatement();
  15. String sql ="SELECT * FROM `users` WHERE `name` = '"+username+"' AND `password` = '"+password+"'";
  16. res = sta.executeQuery(sql);
  17. while (res.next()){
  18. System.out.println(res.getString("name"));
  19. System.out.println(res.getString("password"));
  20. }
  21. } catch (SQLException throwables) {
  22. throwables.printStackTrace();
  23. }finally {
  24. JdbcUtils.release(conn,sta,res);
  25. }
  26. }
  27. }

8、PreparedStatement对象

8.1、编写增删改查类

下面四个例子使用的是上面的工具类:

PreparedStatement可以防止SQL注入,原因是把传递进来的参数当作字符,单引号等转义字符直接被转义忽略。

  1. public class TestInsertPreparedStatement {
  2. public static void main(String[] args){
  3. Connection conn=null;
  4. try {
  5. conn = JdbcUtils.getConnection();
  6. String sql = "INSERT INTO `users`(`id`,`name`,`password`,`email`,`birthday`)VALUE(?,?,?,?,?)";
  7. PreparedStatement sta = conn.prepareStatement(sql);
  8. sta.setInt(1,6);
  9. sta.setString(2,"xiaohong");
  10. sta.setString(3,"123456");
  11. sta.setString(4,"123455@qq.com");
  12. sta.setString(5,"1980-12-21");
  13. int i = sta.executeUpdate();
  14. if (i>0){
  15. System.out.println("插入成功");
  16. }
  17. } catch (SQLException throwables) {
  18. throwables.printStackTrace();
  19. }finally {
  20. JdbcUtils.release(conn,sta,null);
  21. }
  22. }
  23. }
  1. public class TestDelectPreparedStatement {
  2. public static void main(String[] args){
  3. Connection conn=null;
  4. try {
  5. conn = JdbcUtils.getConnection();
  6. String sql = "DELETE FROM users WHERE id = ?";
  7. PreparedStatement sta = conn.prepareStatement(sql);
  8. sta.setInt(1,6);//第一个参数代表占位符,第二个参数是传入id
  9. int i = sta.executeUpdate();
  10. if (i>0){
  11. System.out.println("删除成功");
  12. }
  13. } catch (SQLException throwables) {
  14. throwables.printStackTrace();
  15. }finally {
  16. JdbcUtils.release(conn,sta,null);
  17. }
  18. }
  19. }
  1. public class TestUpdatePreparedStatement {
  2. public static void main(String[] args){
  3. Connection conn=null;
  4. try {
  5. conn = JdbcUtils.getConnection();
  6. String sql = "UPDATE `users` SET `name` = ? WHERE id =?";
  7. PreparedStatement sta = conn.prepareStatement(sql);
  8. sta.setString(1,"xiaohong");//第一个参数代表占位符,第二个参数是传入username
  9. sta.setInt(2,5);//第一个参数代表占位符,第二个参数是传入id
  10. int i = sta.executeUpdate();
  11. if (i>0){
  12. System.out.println("修改成功");
  13. }
  14. } catch (SQLException throwables) {
  15. throwables.printStackTrace();
  16. }finally {
  17. JdbcUtils.release(conn,sta,null);
  18. }
  19. }
  20. }
  1. public class TestSelectPreparedStatement {
  2. public static void main(String[] args){
  3. Connection conn = null;
  4. PreparedStatement sta = null;
  5. ResultSet res =null;
  6. try {
  7. conn = JdbcUtils.getConnection();
  8. String sql = "SELECT * FROM `users` WHERE `name` = ? AND `password` = ?";
  9. sta = conn.prepareStatement(sql);
  10. sta.setString(1,"xiaohong");//第一个参数代表占位符,第二个参数是传入id
  11. sta.setString(2,"123456");//第一个参数代表占位符,第二个参数是传入password
  12. res = sta.executeQuery();
  13. while(res.next()){
  14. System.out.println(res.getString("name"));
  15. System.out.println(res.getString("password"));
  16. }
  17. } catch (Exception throwables) {
  18. throwables.printStackTrace();
  19. }finally {
  20. JdbcUtils.release(conn,sta,res);
  21. }
  22. }
  23. }

8.2、将PreparedStatement提取到工具类

配置信息:

  1. driver=com.mysql.jdbc.Driver
  2. url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false
  3. datebase="jdbcstudy"
  4. username=root
  5. password=123456

工具类:

  1. /*
  2. * 1.这个JDBC工具类包含了数据库的 加载,连接,PreparedStatement的创建,释放资源。
  3. * 2.PreparedStatement这里用的是预加载的方式,调用时需要传入sql语句,然后set值,然后exe执行语句,可以防止sql注入
  4. * 3.下面还有注释里的另一个PreparedStatement方法是用new的方式创建对象,返回的也是这个对象,调用注释里的方法只能去执行sql语句,不能预加载
  5. * */
  6. public class JdbcUtilsP {
  7. private static String driver;
  8. private static String url;
  9. private static String username;
  10. private static String password;
  11. private static String datebase;
  12. static {
  13. try {
  14. InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
  15. Properties properties = new Properties();
  16. properties.load(in);
  17. driver = properties.getProperty("driver");
  18. url = properties.getProperty("url");
  19. username = properties.getProperty("username");
  20. password = properties.getProperty("password");
  21. datebase = properties.getProperty("datebase");
  22. //1.驱动只用加载一次,所以放在static下
  23. Class.forName(driver);
  24. } catch (IOException | ClassNotFoundException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. //2.获取连接
  29. public static Connection getConnection() throws SQLException {
  30. Connection conn = DriverManager.getConnection(url, username, password);
  31. return conn;
  32. }
  33. //3.创建PreparedStatement
  34. public static com.mysql.jdbc.PreparedStatement getPreparedStatement( String sql) {
  35. PreparedStatement ps =null;
  36. try {
  37. Connection conn = JdbcUtilsP.getConnection();
  38. ps = conn.prepareStatement(sql);
  39. } catch (SQLException throwables) {
  40. throwables.printStackTrace();
  41. }
  42. return (com.mysql.jdbc.PreparedStatement) ps;
  43. }
  44. // //3.创建PreparedStatement
  45. // public static com.mysql.jdbc.PreparedStatement getPreparedStatement1() {
  46. // com.mysql.jdbc.PreparedStatement ps =null;
  47. // try {
  48. // ps = new com.mysql.jdbc.PreparedStatement((MySQLConnection) getConnection(),datebase);
  49. // } catch (SQLException throwables) {
  50. // throwables.printStackTrace();
  51. // }finally {
  52. // return ps;
  53. // }
  54. // }
  55. //4.释放资源 注意顺序
  56. public static void release(Connection conn, PreparedStatement ps, ResultSet resultSet) {
  57. if (resultSet!=null){
  58. try {
  59. resultSet.close();
  60. } catch (SQLException throwables) {
  61. throwables.printStackTrace();
  62. }
  63. }
  64. if (ps!=null){
  65. try {
  66. ps.close();
  67. } catch (SQLException throwables) {
  68. throwables.printStackTrace();
  69. }
  70. }
  71. if (conn!=null){
  72. try {
  73. conn.close();
  74. } catch (SQLException throwables) {
  75. throwables.printStackTrace();
  76. }
  77. }
  78. }
  79. }

9、使用IDEA连接数据库

1.如图,找到idea右侧侧边栏的Database,依次按图中的顺序操作。

2..如图,弹出对话框,依次按图中的顺序操作。

3.如图,如果要添加其他数据库,按图中的顺序操作。

4.如图,弹出对话框,依次按图中的顺序操作。

5.如图,修改表中的数据后要点击提交才会成功。

6.如图,需要使用命令行,依次按图中的顺序操作。

7.如果第二步测试连接失败,有可能是下图的原因。

10、操作事务

  1. public class Transaction {
  2. public static void main(String[] args) {
  3. Connection conn = null;
  4. PreparedStatement sta =null;
  5. ResultSet res = null;
  6. try {
  7. conn = JdbcUtils.getConnection();
  8. //1.关闭自动提交,自动会开启事务
  9. conn.setAutoCommit(false);//开启事务
  10. String sql1 = "update account set money-100 where name ='A' ";
  11. sta = conn.prepareStatement(sql1);
  12. sta.executeUpdate();
  13. String sql2 = "update account set money-100 where name ='B' ";
  14. sta = conn.prepareStatement(sql2);
  15. sta.executeUpdate();
  16. //2.业务完毕,提交事务
  17. conn.commit();
  18. System.out.println("成功");
  19. } catch (SQLException throwables) {
  20. try {
  21. //3.数据回滚,如果不写这个也会回滚,不过为了显式定义,写出来较好
  22. conn.rollback();//如果有异常,就会回滚数据
  23. } catch (SQLException e) {
  24. e.printStackTrace();
  25. }
  26. throwables.printStackTrace();
  27. }finally {
  28. JdbcUtils.release(conn,sta,res);
  29. }
  30. }
  31. }

11、数据库连接池

11.1、关于数据库连接池

1.数据库操作流程:数据库连接----执行完毕-----释放资源。

2.其中:数据库连接到释放资源的过程十分浪费系统资源。

3.所以有了池化技术:准备一些预先的资源,过来就连接预先准备好的。

4.举例说明:例如去银行取钱,不用池化技术,就是一个人去办业务,先是开门,然后办理业务,然后走了关门,如果再来人,也是这样的操作,一直重复的去开门关门。这显然不符合现实规律。正确的操作应该是一个人去办业务,银行会预先由几个业务员等待,人来了先是开门,然后办业务,然后走人,门不会关,继续等下一个人,直到我们什么时候下班才会真正的关门。

5.对于数据库也是如此,我们要考虑的是“业务员”(连接数)要设置多少才合适,应该是常用连接数是多少,我们最小链接数就应该设置多少。

6.开源数据实现:DBCP、C3P0、Druid。

使用了这些数据库连接池之后,我们在项目开发中就不需要编写连接数据库的代码了。

11.2、DBCP:

在书写代码方面为我们简化了工具类代码,不需要用Properties一个一个从配置文件中读取信息初始化,而是加载完properties文件后,直接用dataSource = BasicDataSourceFactory.createDataSource(properties);创建数据源。且不需要加载驱动。第二步的连接数据库也不需要用DriverManager,而是直接使用dataSource去getgetConnection()连接数据库。

  • 需要用到的jar包:commons-dbcp-1.4.jar、commons-pool-1.6.jar。
  • 具体操作:

1.配置文件dbcpconfig.properties

  1. #连接设置,这里面的名字是DBCP数据源中定义好的
  2. driverClassName=com.mysql.jdbc.Driver
  3. url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false
  4. username=root
  5. password=123456
  6. #<!-- 初始化连接-->
  7. initialSize=10
  8. #最大连接数量
  9. maxActive=50
  10. #最大空闲连接
  11. maxIdle=20
  12. #最小空闲连接
  13. minIdle=5
  14. #超时等待时间以毫秒为单位/s
  15. maxWait=60000
  16. #JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;]
  17. #注意:“user” 与 “password” 两个属性会被明确地传递,因此这里不需要包含他们。
  18. connectionProperties=useUnicode=true;characterEncoding=utf8
  19. #指定由连接池所创建的连接的自动提交(auto-commit)状态。
  20. defaultAutoCommit=true
  21. #driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
  22. #可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
  23. defaultTransactionIsolation=READ_UNCOMMITTED

2.编写工具类JdbcUtils_DBCP

  1. public class JdbcUtils_DBCP {
  2. private static DataSource dataSource = null;
  3. static {
  4. try {
  5. InputStream in=JdbcUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");//读取配置文件
  6. Properties properties = new Properties();
  7. properties.load(in);
  8. //创建数据源 工厂模式
  9. dataSource = BasicDataSourceFactory.createDataSource(properties);
  10. } catch (Exception e) {
  11. e.printStackTrace();
  12. }
  13. }
  14. //2.获取连接
  15. public static Connection getConnection() throws SQLException {
  16. return dataSource.getConnection();//从数据源获取连接
  17. }
  18. //3.创建PreparedStatement
  19. public static PreparedStatement getPreparedStatement( String sql) {
  20. PreparedStatement ps =null;
  21. try {
  22. Connection conn = JdbcUtils_DBCP.getConnection();
  23. ps = conn.prepareStatement(sql);
  24. } catch (SQLException throwables) {
  25. throwables.printStackTrace();
  26. }
  27. return ps;
  28. }
  29. //4.释放资源 注意顺序
  30. public static void release(Connection conn, PreparedStatement ps, ResultSet resultSet) {
  31. if (resultSet!=null){
  32. try {
  33. resultSet.close();
  34. } catch (SQLException throwables) {
  35. throwables.printStackTrace();
  36. }
  37. }
  38. if (ps!=null){
  39. try {
  40. ps.close();
  41. } catch (SQLException throwables) {
  42. throwables.printStackTrace();
  43. }
  44. }
  45. if (conn!=null){
  46. try {
  47. conn.close();
  48. } catch (SQLException throwables) {
  49. throwables.printStackTrace();
  50. }
  51. }
  52. }
  53. }

3.测试代码

  1. public class TestDBCP {
  2. public static void main(String[] args) throws SQLException {
  3. Connection conn = JdbcUtils_DBCP.getConnection();
  4. String sql = "insert into `users`(`id`,`name`,`password`,`email`,`birthday`)value(?,?,?,?,?)";
  5. PreparedStatement ps = JdbcUtils_DBCP.getPreparedStatement(sql);
  6. ps.setInt(1,7);
  7. ps.setString(2,"sss");
  8. ps.setString(3,"123456");
  9. ps.setString(4,"3425@qq.com");
  10. ps.setString(5,"1999-09-09");
  11. int i = ps.executeUpdate();
  12. if (i>0){
  13. System.out.println("插入成功");
  14. }
  15. JdbcUtils_DBCP.release(conn,ps,null);
  16. }
  17. }

11.3、C3P0:

在书写代码上,相较于DBCP,C3P0更加简化了代码,连加载properties文件都不需要了,静态代码直接用dataSource= new ComboPooledDataSource("MySQL");一句代码即可,然后剩下的代码同前面一样。

  • 需要用到的jar包:c3p0-0.9.5.5.jar、mchange-commons-java-5.1.47.jar。
  • 具体操作:

1.配置文件c3p0-config.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <c3p0-config>
  3. <default-config>
  4. <!--
  5. C3P0的缺省(默认)配置,
  6. 如果在代码中是 ComboPooledDataSource cp = new ComboPooledDataSource(); 这样写是default-config的配置
  7. -->
  8. <property name="driverClass">com.mysql.jdbc.Driver</property>
  9. <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcsstudy?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false</property>
  10. <property name="user">root</property>
  11. <property name="password">123456</property>
  12. <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
  13. <property name="acquireIncrement">3</property>
  14. <!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 10 这些都是自己定义 -->
  15. <property name="initialPoolSize">10</property>
  16. <!-- 连接的最大空闲时间,default: 30 -->
  17. <property name="maxIdleTime">30</property>
  18. <!--连接池中保留的最大连接数。Default: 100 -->
  19. <property name="maxPoolSize">100</property>
  20. <!--连接池中保留的最小连接数。Default: 15 -->
  21. <property name="minPoolSize">15</property>
  22. </default-config>
  23. <!--
  24. C3P0的命名配置,
  25. 如果在代码中是 ComboPooledDataSource cp = new ComboPooledDataSource("MySQL"); 这样写是default-config的配置
  26. -->
  27. <named-config name="MySQL">
  28. <property name="driverClass">com.mysql.jdbc.Driver</property>
  29. <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false</property>
  30. <property name="user">root</property>
  31. <property name="root">123456</property>
  32. <property name="acquireIncrement">3</property>
  33. <property name="initialPoolSize">10</property>
  34. <property name="maxIdleTime">30</property>
  35. <property name="maxPoolSize">100</property>
  36. <property name="minPoolSize">10</property>
  37. </named-config>
  38. <!-- 所以下面想什么配置就写什么配置 -->
  39. </c3p0-config>

2.编写工具类JdbcUtils_C3P0

  1. public class JdbcUtils_C3P0 {
  2. private static ComboPooledDataSource dataSource=null;
  3. static {
  4. try {
  5. /* //代码配置,麻烦不用
  6. dataSource = new ComboPooledDataSource();
  7. dataSource.setDriverClass("com.mysql.jdbc.Driver");
  8. dataSource.setUser("root");
  9. dataSource.setPassword("123456");
  10. dataSource.setMaxPoolSize(100);
  11. dataSource.setMinPoolSize(10);*/
  12. //配置文件的配法,我们只要导入xml文件,写个一句就好了
  13. dataSource= new ComboPooledDataSource("MySQL");//这里的参数不写用的是配置文件中默认的数据源,如有其他需求,就传入需要的named-config
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. //2.获取连接
  19. public static Connection getConnection() throws SQLException {
  20. return dataSource.getConnection();//从数据源中获取连接
  21. }
  22. //3.释放资源
  23. public static void release(Connection conn, Statement st, ResultSet rs) {
  24. if (rs!=null){
  25. try {
  26. rs.close();
  27. } catch (SQLException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. if (st!=null){
  32. try {
  33. st.close();
  34. } catch (SQLException e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. if (conn!=null){
  39. try {
  40. conn.close();
  41. } catch (SQLException e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. }
  46. }

3.测试代码

  1. public class TestC3P0 {
  2. public static void main(String[] args) {
  3. Connection conn = null;
  4. PreparedStatement ps = null;
  5. ResultSet rs = null;
  6. try {
  7. conn = JdbcUtils_C3P0.getConnection();
  8. String sql = "INSERT INTO users(`id`,`NAME`,`PASSWORD`,`email`,`birthday`) VALUES(?,?,?,?,?)";
  9. ps = conn.prepareStatement(sql);
  10. ps.setInt(1, 27);
  11. ps.setString(2, "我爱你");
  12. ps.setString(3, "1314");
  13. ps.setString(4, "804328977@qq.com");
  14. ps.setDate(5, new Date(new java.util.Date().getTime()));
  15. int i = ps.executeUpdate();
  16. if (i > 0) {
  17. System.out.println("插入成功o(*▽*)q");
  18. }
  19. } catch (SQLException e) {
  20. e.printStackTrace();
  21. } finally {
  22. JdbcUtils_DBCP.release(conn, ps, rs);
  23. }
  24. }
  25. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/722122
推荐阅读
相关标签
  

闽ICP备14008679号