jdbc 获取connection 对象的三种方式

获取数据库连接方法一:驱动实现类

 1             //创建mysql的Driver对象
 2             Driver driver=new com.mysql.jdbc.Driver();
 3             //jdbc url  定位一个数据库:
 4             String url="jdbc:mysql://localhost:3306/jdbcdb";
 5             //用于存储用户名和密码
 6             Properties info=new Properties();
 7             info.put("user", "root");//key值确定——“user”
 8             info.put("password", "mysql");
 9             //获得连接对象
10             Connection connection= driver.connect(url, info);
11             System.out.println(connection);                        

获取数据库连接方法二:驱动管理器注册

1 //向驱动管理器注册驱动  ——把mysql驱动对象类的对象放置在集合中
2             DriverManager.registerDriver(new com.mysql.jdbc.Driver());
3             
4             String url="jdbc:mysql://localhost/jdbcdb";
5             //获取连接  ——先从集合中获取驱动,再调用驱动
6             Connection connection= DriverManager.getConnection(url, "root", "mysql");
7             System.out.println(connection);

获取数据库连接方法三:加载驱动类字节码

 1 try {
 2             //加载jdbc的驱动类名
 3             Class.forName("com.mysql.jdbc.Driver");
 4         } catch (ClassNotFoundException e) {
 5             // TODO Auto-generated catch block
 6             e.printStackTrace();
 7         }
 8         
 9         try {
10             String url="jdbc:mysql://localhost/jdbcdb";
11             //获取连接
12             Connection connection= DriverManager.getConnection(url, "root", "mysql");
13             System.out.println(connection);
14         } catch (SQLException e) {
15             // TODO Auto-generated catch block
16             e.printStackTrace();
17         }

 

转载于:https://www.cnblogs.com/liuwt365/p/4095201.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值