jdbc连接数据库总结

来源:互联网 发布:winscp mac版下载 编辑:程序博客网 时间:2024/06/05 20:13

jdbc连接数据库


//连接数据库的URL
private String url = “jdbc:mysql://localhost:3306/day17”;
// jdbc协议:数据库子协议:主机:端口/连接的数据库 //
private String user = “root”;//用户名
private String password = “root”;//密码

方法一:

@Test
public void test1() throws Exception{
//1.创建驱动程序类对象
Driver driver = new com.mysql.jdbc.Driver(); //新版本
//设置用户名和密码
Properties props = new Properties();
props.setProperty(“user”, user);
props.setProperty(“password”, password);
//2.连接数据库,返回连接对象
Connection conn = driver.connect(url, props);
System.out.println(conn);
}

方法二:使用驱动管理器类连接数据库(注册了两次)

/**
* 使用驱动管理器类连接数据库(注册了两次,没必要)
* @throws Exception
*/

@Testpublic void test2() throws Exception{    Driver driver = new com.mysql.jdbc.Driver();    //1.注册驱动程序(可以注册多个驱动程序)    **DriverManager**.registerDriver(driver);    //2.连接到具体的数据库    Connection conn = **DriverManager**.getConnection(url, user, password);}

方法三:使用加载驱动程序类来注册驱动程序(推荐)

@Test
public void test3() throws Exception{
//Driver driver = new com.mysql.jdbc.Driver();

    //通过得到字节码对象的方式加载静态代码块,从而注册驱动程序    Class.forName("com.mysql.jdbc.Driver");     //2.连接到具体的数据库    Connection conn = DriverManager.getConnection(url, user, password);}

原创粉丝点击