目录
连接方式一:drive创建对象需要导入jar包(第三方API)
连接方式一:drive创建对象需要导入jar包(第三方API)
@Test
//第一种连接方式
public void test() throws Exception {
//获取Driver实现类对象,也可导入此类,在这里写出只是更好说明此类路径
com.mysql.jdbc.Driver driver = new com.mysql.jdbc.Driver();
/*
* url:类似于http地址,用于连接指定数据库,前半截不变,后面test表示你的数据库的名称;
* jdbc:mysql:协议
* localhost:IP地址
* 3306:mysql默认端口号
* test:数据库名
*/
String url = "jdbc:mysql://localhost:3306/test";
//将数据名和密码封存在Properties中
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "6868");
//获取连接
Connection conn = driver.connect(url, info);
System.out.println(conn);
}
连接方式二:
/*第二种连接方式:对于第一种方式的迭代,使得程序中不再出现第三方的API,
使程序具有更好的可移植性*/
@Test
public void test02() throws Exception {
//1.获取Driver实现类对象,在这里使用反射
Class clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
//2.提供要连接的数据库
String url = "jdbc:mysql://localhost:3306/test";
//3.提供连接需要的用户名和密码
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "6868");
//4.获取数据库连接
Connection conn = driver.connect(url, info);
System.out.println(conn);
}
连接方式三:
//方式三:使用DriverManagement替换Driver
@Test
public void test03() throws Exception {
//1.获取Driver实现类对象,在这里使用反射
Class clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
//2.获取连接的3个对象信息
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "6868";
//3.注册驱动
DriverManager.registerDriver(driver);
//4.获取数据库连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
连接方式四:
//方式四
@Test
public void test04() throws Exception {
//1.获取连接的3个对象信息
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "6868";
//2.加载Driver,内置静态代码块,可自动加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
// //3.注册驱动
// DriverManager.registerDriver(driver);
//3.获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
连接方式五:
新建一个properties文件保存基本信息
//方式五
@Test
public void test05() throws IOException, ClassNotFoundException, SQLException {
//1.读取配置文件的4个基本信息
InputStream is = MyConnection.class.getClass().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String url = pros.getProperty("url");
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String driverClass = pros.getProperty("driverClass");
//2.加载驱动
Class.forName(driverClass);
//3.获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}