Java使用Driver驱动程序连接数据库的具体实现:
- 创建Driver驱动程序实例
Driver driver=new com.mysql.cj.jdbc.Driver(); - 准备连接数据库所需要的请求参数
url,user,password等 - 使用Driver驱动的connect方法连接数据库
driver.connect(url,info);
下面给出两种方法,第一种比较有局限性(与MySQL紧密耦合),推荐使用第二种(通用方法,只需要修改配置文件即可连接其他数据库)
源代码
第一种
package lesson1;
import static org.junit.Assert.*;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;
import org.junit.Test;
public class JDBCtest {
@Test
public void test(){
//fail("Not yet implemented");
String url="jdbc:mysql://localhost:3306/world?serverTimezone=UTC";//url
Properties info=new Properties();//键值对信息属性
//输入键值对信息
info.put("user","root");
info.put("password","******");
try {
Driver driver = new com.mysql.cj.jdbc.Driver();//创建连接MySQL驱动接口
Connection connection=driver.connect(url, info);//返回连接借口对象
System.out.println(connection);
} catch (SQLException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
第二种
package lesson1;
import static org.junit.Assert.*;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;
import org.junit.Test;
public class JDBCtest {
public Connection getConnection()
{
//准备数据
String driverClass=null;
String url=null;
String user=null;
String password=null;
Properties info=new Properties();
Connection connection=null;//连接接口对象
try {
//读入配置文件数据
FileReader fis=new FileReader("E:\\Files\\eclipse-workspace\\JDBC\\src\\lesson1\\JDBCvalue.txt");
BufferedReader bis=new BufferedReader(fis);
ArrayList<String> inputList=new ArrayList<String>();
String str;
while((str=bis.readLine())!=null)
{
inputList.add(str);
}
bis.close();
driverClass=inputList.get(0);
url=inputList.get(1);
user=inputList.get(2);
password=inputList.get(3);
//键值对
info.put("user",user);
info.put("password",password);
Driver driver=(Driver) Class.forName(driverClass).newInstance();//创建连接MySQL驱动接口
connection = driver.connect(url, info);//返回连接接口对象
}catch (IOException e1) {
e1.printStackTrace();
}catch (SQLException e) {
System.out.println(e.getMessage());
}catch (InstantiationException e) {
System.out.println(e.getMessage());
} catch (IllegalAccessException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
return connection;
}
@Test
public void testgetConnection()
{
System.out.println(getConnection());
}
}