Java简单的数据库连接
public class TestConnte {
//连接数据库的URL
private String url = "jdbc:mysql://localhost:3306/demo";
// jdbc协议:数据库子协议:主机:端口/连接的数据库 //
private String user = "root";//用户名
private String password = "123456";//密码
@Test
public void test() throws Throwable {
//1.创建驱动程序类对象
Driver driver = new com.mysql.jdbc.Driver(); //新版本(MySQL数据库)
//Driver driver = new org.gjt.mm.mysql.Driver(); //旧版本
//Driver driver2 = new com.oracle.jdbc.Driver();//(oracle数据库)
//设置用户名和密码
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", password);
//注册驱动程序(可以注册多个驱动程序)
//DriverManager.registerDriver(driver);
//2.连接数据库,返回连接对象
Connection conn = driver.connect(url, props);
System.out.println(conn);
}
/**
* (推荐使用这种方式连接数据库)
* 推荐使用加载驱动程序类 来 注册驱动程序
*/
@Test
public void test2() throws Exception{
//通过得到字节码对象的方式加载静态代码块,从而注册驱动程序
Class.forName("com.mysql.jdbc.Driver");
//.连接到具体的数据库
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
}
需要引用的jar
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>