下面的程序介绍了如何通过jdbc获得数据库的连接,第一个测试方法DriverTest() 是原生的java通过jdbc连接mysql数据库的一种方法,第二个测试方法CommondriverTest()是通过类路径下的配置文件来获得连接信息,从而获得连接,这种方法不局限于某种特定的数据库,而是通用的,只需要改变配置文件即可。
import java.io.IOException;
import java.io.InputStream;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import org.junit.Test;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Driver;
public class JDBCTest
{
@Test
public void DriverTest() throws SQLException, ClassNotFoundException
{
Driver driver = new com.mysql.jdbc.Driver();
<span style="color:#ff0000;">/* Class.forName("com.mysql.jdbc.Driver");
* 该句和上句效果相同,因为在载入Driver类的时候,在实现的静态代码块中,Driver接口会自动的创建Driver对象,
* 并自动在DriverManager中进行注册。
* 附:Driver中的静态代码块:
* static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
*/
</span>
String url = "jdbc:mysql://127.0.0.1:3306/jdbcdb";
Properties info = new Properties(); //properties继承于HashTable,表示一个键值对
info.put("user","root");
info.put("password","root");
<span style="color:#ff0000;">/*
* Connection con = (Connection) DriverManager.getConnection(url,info);
* 该句对应上面注释的Class.forName(...);来获得一个连接。
* 在jdbc4之后,其实可以不用使用上面的Class.forName(...);,DriverManager在getConnection的时候,
* 会自动的加载合适的驱动。
*/
</span>
Connection con = (Connection) driver.connect(url,info);
System.out.println(con);
}
//下面的是一个通用的类来获取任意一种数据库的连接的方式,它通过读取jdbc.properties配置文件来获取相应的连接信息(driverClass,url,user,password)
public Connection getConnection() throws ClassNotFoundException, SQLException, IOException
{
String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null;
//读取类路径下的jdbc.properties文件
InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(in);
driverClass = properties.getProperty("driver");
jdbcUrl = properties.getProperty("jdbcUrl");
user = properties.getProperty("user");
password = properties.getProperty("password");
Properties info = new Properties();
info.put("user",user);
info.put("password",password);
//加载Driver类,并获得连接
Class.forName(driverClass);
Connection con = (Connection) DriverManager.getConnection(jdbcUrl,info);
return con;
}
@Test
public void CommondriverTest() throws ClassNotFoundException, SQLException, IOException
{
System.out.println(getConnection());
}
}
配置信息如下:
<pre class="html" name="code">driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/jdbcdb
user=root
password=root