jdbc 数据库连接
连接数据库
1)通过Driver来连接(Driver:数据库厂商提供的一个接口)
public void testDriver()throws Exception{
Driver driver = new com.mysql.jdbc.Driver();
String Url = "jdbc:mysql://localhost:3306/test_user";//地址(jdbcUrl)
Properties properties = new Properties();//连接数据库所需要的信息
properties.put("user","user");
properties.put("password","password");
Connection con = driver.connect(Url,properties);
}
Driver:通过配置文件来连接
public Connection getConnection() throws Exception{
String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null;
//读取类路径下的properties
InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");//创建输入流
Properties properties = new Properties();
properties.load(in);//载入
driverClass=properties.getProperty("driver");//获取key为“driver”的值
jdbcUrl = properties.getProperty("jdbcUrl");
user = p.getProperty("user");
password = p.getProperty("password");
Driver driver = (Driver) Class.forName(driverClass).newInstance();//实例化
Properties info = new Properties();
info.put("user",user);
info.put("password",password);
Connection connection = driver.connect(jdbcUrl, info);
return connection;
}
jdbc.properties文件:
driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/test_user
user=root
password=
2)通过DriverManager连接数据库
//DriverManager是驱动类管理:
//1、可以通过带重载getConnection()的方法获取数据库连接,
//2、可以同时管理多个驱动程序:因为getConnection()中有一个类是DriverInfo
public void testDriverManager() throws Exception{
//1.准备连接数据库的4个参数,
//a.驱动全类名
String driverClass = null;
//b.jdbcUrl
String jdbcUrl = null;
//c.user
String user = null;
//d.password
String password = null;
//读取类路径下的properties
InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties p = new Properties();
p.load(in);
driverClass=p.getProperty("driver");
jdbcUrl = p.getProperty("jdbcUrl");
user = p.getProperty("user");
password = p.getProperty("password");
//2.加载驱动程序(注册驱动)
//这里不用写“DriverManager.registerDriver(Class.forName(driverClass)),Driver有静态代码块(可以注册不同的驱动),已经注册过了”
Class.forName(driverClass);//加载数据库驱动,
//3.通过DriverManager获取数据库连接
Connection connection = DriverManager.getConnection(jdbcUrl,user,password);
}
以上方式,总觉的很麻烦,如果没有用框架的话,可以直接写死
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_user","root","");