1 /**
2 * jdbc连接数据库
3 * @author APPle
4 *
5 */
6 public class Demo1 {
7 //连接数据库的URL
8 private String url = "jdbc:mysql://localhost:3306/demo1";
9 // jdbc协议:数据库子协议:主机:端口/连接的数据库 //
10
11 private String user = "root";//用户名
12 private String password = "root";//密码
13
14 /**
15 * 第一种方法
16 * @throws Exception
17 */
18 @Test
19 public void test1() throws Exception{
20 //1.创建驱动程序类对象
21 Driver driver = new com.mysql.jdbc.Driver(); //新版本
22 //Driver driver = new org.gjt.mm.mysql.Driver(); //旧版本
23
24 //设置用户名和密码
25 Properties props = new Properties();
26 props.setProperty("user", user);
27 props.setProperty("password", password);
28
29 //2.连接数据库,返回连接对象
30 Connection conn = driver.connect(url, props);
31
32 System.out.println(conn);
33 }
34
35 /**
36 * 使用驱动管理器类连接数据库(注册了两次,没必要)
37 * @throws Exception
38 */
39 @Test
40 public void test2() throws Exception{
41 Driver driver = new com.mysql.jdbc.Driver();
42 //Driver driver2 = new com.oracle.jdbc.Driver();
43 //1.注册驱动程序(可以注册多个驱动程序)
44 DriverManager.registerDriver(driver);
45 //DriverManager.registerDriver(driver2);
46
47 //2.连接到具体的数据库
48 Connection conn = DriverManager.getConnection(url, user, password);
49 System.out.println(conn);
50
51 }
52
53 /**
54 * (推荐使用这种方式连接数据库)
55 * 推荐使用加载驱动程序类 来 注册驱动程序
56 * @throws Exception
57 */
58 @Test
59 public void test3() throws Exception{
60 //Driver driver = new com.mysql.jdbc.Driver();
61
62 //通过得到字节码对象的方式加载静态代码块,从而注册驱动程序
63 Class.forName("com.mysql.jdbc.Driver");
64
65 //Driver driver2 = new com.oracle.jdbc.Driver();
66 //1.注册驱动程序(可以注册多个驱动程序)
67 //DriverManager.registerDriver(driver);
68 //DriverManager.registerDriver(driver2);
69
70 //2.连接到具体的数据库
71 Connection conn = DriverManager.getConnection(url, user, password);
72 System.out.println(conn);
73
74 }
75
76 }