jar包可百度下载
方式一:
public void test01() throws SQLException, ClassNotFoundException {
//获取Driver的实现类对象
Driver driver=new com.mysql.cj.jdbc.Driver();
Properties info=new Properties();
String url="jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useSSL=false";
info.setProperty("user", "root");
info.setProperty("password", "123456");//这里就是你自己数据库的密码了
Connection con2 = driver.connect(url, info);
System.out.println(con2);
}
方式二:
不出现第三方的API 使用反射
public void test02() throws SQLException, Exception {
//获取Driver的实现类对象
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver)clazz.getDeclaredConstructor().newInstance();
//提供要连接的数据库
String url="jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useSSL=false";
Properties info=new Properties();
info.setProperty("user", "root");
info.setProperty("password", "123456");
Connection con2 = driver.connect(url, info);
System.out.println(con2);
}
方式三: 使用DriverManager
public void test03() throws SQLException, Exception {
//获取Driver实现类对象
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver)clazz.getDeclaredConstructor().newInstance();
//2.提供另外的三个连接信息
String url="jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useSSL=false";
String user="root";
String passwd="123456";
//注册驱动
DriverManager.registerDriver(driver);
Connection connection = DriverManager.getConnection(url,user,passwd);
System.out.println(connection);
}
方式四:
简化
//1.提供另外的三个连接信息
String url="jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useSSL=false";
String user="root";
String passwd="123456";
//快捷键alt+上下可移动代码
//2、获取Driver实现类对象 静态代码块随着类的加载而执行
Class.forName("com.mysql.cj.jdbc.Driver");//这一步也是可省略的但只适用于mysql
//可以省略
//Driver driver = (Driver)clazz.getDeclaredConstructor().newInstance();
//注册驱动
//DriverManager.registerDriver(driver);
//为什么可以省略
/*
* 在mysql的Driver实现类中,声明了如下的操作:
* static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
会自动注册驱动
*/
//3 获取连接 alt+/
Connection connection = DriverManager.getConnection(url,user,passwd);
System.out.println(connection);
}
方式五:将数据库连接需要的4个基本信息声明在配置文件中,通过读取配置文件的方式,获取连接
此种方式的好处
- 1.实现了数据与代码的分离。实现了解耦
- 2.如果需要修改配置文件信息,可以避免程序重新打包
public static void test05() throws SQLException, Exception {
//获取配置信息
InputStream stream = contest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(stream);
String str1 = pros.getProperty("url");
String str2 = pros.getProperty("user");
String str3 = pros.getProperty("passwd");
String str4 = pros.getProperty("driverClass");
//加载驱动
Class.forName(str4);
//获取连接
Connection conn = DriverManager.getConnection(str1, str2, str3);
}
来源:CSDN
作者:睡什么觉,起来打代码
链接:https://blog.csdn.net/qq_42193790/article/details/104648159