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         }

 

posted @ 2014-11-13 16:09  liuwt365  阅读(2121)  评论(0编辑  收藏  举报