五种方法属于递进关系,推荐使用第五种方法,其余四种学习使用
先了解一下自己的数据库信息
查看一下此链接下的数据库
方法一
@Test
public void test() throws SQLException {
// 获取driver实现类对象
Driver driver = new com.mysql.jdbc.Driver();
// url地址
String url = "jdbc:mysql://localhost:3306/demo";//要记得改成自己表所在的库,(我的是demo库)
// 封装用户对象
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "111111");//数据库密码为自己所设 我的为111111
Connection conn = driver.connect(url, info);
System.out.println(conn);
}
方法二
// 方法二
@Test
public void test2() throws Exception {
// 获取driver实现类对象 反射
Class clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
// 提供数据库
String url = "jdbc:mysql://localhost:3306/demo";//要记得改成自己表所在的库,(我的是demo库)
// 封装用户对象
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "111111");//数据库密码为自己所设 我的为111111
// 获取链接
Connection conn = driver.connect(url, info);
System.out.println(conn);
}
方法三
// 方式三
@Test
public void test3() throws Exception {
// driver
Class clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
// 三个链接
String url = "jdbc:mysql://localhost:3306/demo";//要记得改成自己表所在的库,(我的是demo库)
String user = "root";
String password = "111111";//数据库密码为自己所设 我的为111111
// 注册驱动
DriverManager.registerDriver(driver);
// 获取链接
DriverManager.getConnection(url, user, password);
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
方法四
// 方法四
@Test
public void test4() throws Exception {
// 三个链接
String url = "jdbc:mysql://localhost:3306/demo";//要记得改成自己表所在的库,(我的是demo库)
String user = "root";
String password = "111111";//数据库密码为自己所设 我的为111111
// driver
Class.forName("com.mysql.jdbc.Driver");//此行可以省略 但不建议
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
方法五
在src目录下创建file文件
file文件内填入user、password、url、driver(顺序无所谓)
user=root
password=111111 #自己数据库的密码我的是111111
url=jdbc:mysql://localhost:3306/demo #url里用的是自己建的库,要记得改成自己表所在的库,(我的是demo库)
driver=com.mysql.jdbc.Driver
.java文件里的方法
//最终方法 配置文件法
//数据代码分离
@Test
public void getConnection5() throws Exception {
//读取信息
InputStream is = test.class.getClassLoader().getSystemResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driver = pros.getProperty("driver");
//加载驱动
Class.forName(driver);
//获取链接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}