方式一:调用driver的connect方法获取连接
@Test
public void testConnection1() throws SQLException
{
//获取Driver的实现类对象
try {
Driver driver=new com.mysql.jdbc.Driver();//com.mysql.jdbc.Driver()第三方的API
//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", "abc123");
Connection conn=driver.connect(url, info);
System.out.println(conn);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
方式一的不足:显式出现了第三方数据库的API(最好用到的都是sun公司自己的API)
方式二:在方式一的基础上迭代
@Test
public void testConnection2() 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", "abc123");
//4.获取连接
Connection conn=driver.connect(url, info);
System.out.println(conn);
}
方式二用到了反射实例化driver类的对象,使程序具有更好的移植性,用到的都是sun公司自己的API
并且体现了面向接口编程的思想
方式三:使用DriverManager类替换Driver
@Test
public void testConnection3() 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";
String user="root";
String password="abc123";
//注册驱动
DriverManager.registerDriver(driver);
//获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
连接必备的四要素:url、user、password、drivername
这种方式需要显式的注册驱动
方式四:方式三的基础上改进 可以不用注册驱动 只是加载驱动
@Test
public void testConnection4() throws Exception
{
//1.提供另外三个连接的基本信息
String url="jdbc:mysql://localhost:3306/test";
String user="root";
String password="abc123";
//2.获取Driver的实现类对象
Class.forName("com.mysql.jdbc.Driver");
//获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
可以不用加载驱动的原因:
//在Driver实现类中声明了如下的操作
static
{
try{
java.sql.DriverManager.registerDriver(new Driver());
}catch{
...
}
}
方式五:使用配置文件
在配置文件jdbc.properties中(声明在工程的src目录下)
user=root
password=abc123
url=jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true
driverClass=com.mysql.jdbc.Driver
注意:在url中把rewriteBatchedStatements参数置为true,可以批量执行SQL。
@Test
public void testConnection5() throws Exception
{
//1.读取配置文件中的4个基本信息
InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("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 driverClass = pros.getProperty("driverClass");
//2.加载驱动
Class.forName(driverClass);
//3.获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
这种方式的好处:1. 实现了数据与代码的分离,实现了解耦(改动改在配置文件,不用动代码)
2.如果需要修改配置文件信息,可以避免程序重新打包,省去重新编译的过程