使用JDBC连接mysql的三种方式

素颜马尾好姑娘i 2023-10-04 09:50 131阅读 0赞

JDBC连接mysql的三种方式

(Java DataBase Connectivity)是一个独立于特定数据库管理系统,通用的SQL数据库存取和操作的公共接口(一组api)

JDBC为访问不同的数据库提供了一种统一的途径

JDBC连接数据库

首先:导入jar包

IDEA中在File -> Project Structure ->Libraries ->java 实现导包功能

方式一:
  1. public void testConnection1() throws SQLException {
  2. Driver driver = new com.mysql.jdbc.Driver();
  3. //jdbc:mysql:协议
  4. //localhost:IP地址
  5. //3306:端口号
  6. //test:test数据库
  7. String url = "jdbc:mysql://localhost:3306/test";
  8. //将用户名和密码封装到Properties中
  9. Properties info = new Properties();
  10. info.setProperty("user","root");
  11. info.setProperty("password","1234");
  12. Connection conn = driver.connect(url,info);
  13. System.out.println(conn);
  14. }
方式二:对方式一的迭代,是程序不出现第三放API
  1. public void testConnection2() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
  2. //1、获取Driver实现类对象,使用反射
  3. Class clazz = Class.forName("com.mysql.jdbc.Driver");
  4. Driver driver = (Driver) clazz.newInstance();
  5. //2、提供要连接的数据库
  6. String url = "jdbc:mysql://localhost:3306/test";
  7. //3、提供连接需要的用户名和密码
  8. Properties info = new Properties();
  9. info.setProperty("user","root");
  10. info.setProperty("password","1234");
  11. //4、获取连接
  12. Connection conn = driver.connect(url, info);
  13. System.out.println(conn);
  14. }
方式三:使用DriverManager替换Driver
  1. public void testConnection3() throws Exception{
  2. //1、获取Driver实现类对象
  3. Class clazz = Class.forName("com.mysql.jdbc.Driver");
  4. Driver driver = (Driver) clazz.newInstance();
  5. //2、提供三个连接信息
  6. String url = "jdbc:mysql://localhost:3306/test";
  7. String user = "root";
  8. String password = "1234";
  9. //3、注册驱动
  10. DriverManager.registerDriver(driver);
  11. //4、连接数据库
  12. Connection connection = DriverManager.getConnection(url, user, password);
  13. System.out.println(connection);
  14. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,131人围观)

还没有评论,来说两句吧...

相关阅读

    相关 PHP连接mysql方式

    主要分为两种,一是通过MYSQLI方式,另外是通过PDO MYSQLI方式只能连接mysql数据库,而PDO方式可以连接12种数据库,便于数据库切换 一、MYSQLI方式