首先要导入jar包(必须且重要)
将jar包复制到工程目录之后 右键选择 Add as Library..
方式1:
public class ConnectionTest {
@Test
public void test() throws SQLException {
Driver driver = new com.mysql.cj.jdbc.Driver();
String url = "jdbc:mysql://localhost:3306/atguigudb";
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("password","root");
Connection connection = driver.connect(url, info);
System.out.println(connection);
}
}
方式2:在程序中不出现第三方api 使程序具有更好的可移植性
public class ConnectionTest {
@Test
public void test() throws Exception {
//使用反射来获取Driver实现类对象
Class aClass = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) aClass.getDeclaredConstructor().newInstance();
//提供要连接的数据库
String url = "jdbc:mysql://localhost:3306/atguigudb";
//提供要连接数据库的用户名和密码
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("password","root");
//获取连接
Connection connection = driver.connect(url, info);
System.out.println(connection);
}
}
方式3:使用DriverManger替换Driver
public class ConnectionTest {
@Test
public void test() throws Exception {
//使用反射来获取Driver实现类对象
Class aClass = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) aClass.getDeclaredConstructor().newInstance();
//提供另外三个连接的基本信息
String url = "jdbc:mysql://localhost:3306/atguigudb";
String user="root";
String password="root";
//注册驱动
DriverManager.registerDriver(driver);
//获取连接
DriverManager.getConnection(url,user,password);
//获取连接
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println(connection);
}
}
方式4:可以只是加载驱动 不用显示的注册驱动
public class ConnectionTest {
@Test
public void test() throws Exception {
//加载Driver 因为mysql的driver实现类中 有一段代码块
Class.forName("com.mysql.cj.jdbc.Driver");
//提供另外三个连接的基本信息
String url = "jdbc:mysql://localhost:3306/atguigudb";
String user="root";
String password="root";
//获取连接
DriverManager.getConnection(url,user,password);
//获取连接
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println(connection);
}
}
方式5:将数据库连接需要的4个基本信息生命在配置文件中 通过读取配置文件的方式 获取连接
public class ConnectionTest {
@Test
public void test() throws Exception {
//读取配置文件中的4个基本信息
InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties pro = new Properties();
pro.load(is);
String user = pro.getProperty("user");
String url = pro.getProperty("url");
String password = pro.getProperty("password");
String driverClass = pro.getProperty("driverClass");
Class.forName("com.mysql.cj.jdbc.Driver");
//获取连接
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println(connection);
}
}
jdbc.properties
url=jdbc:mysql://localhost:3306/atguigudb
user=root
password=root
driverClass=com.mysql.cj.jdbc.Driver