(一)建配置文件连接数据库

  1、首先导入jar包mysql-5.1.26-bin.jar

  2、在src下新建file命名为dbconfig.properties,添加内容driverClassName,url,username,password

  driverClassName=com.mysql.jdbc.driver

  url=jdbc:mysql://localhost:3306/stu

  username=root

  password=123

  3、新建JdbcUtils.java类

 

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

 

import java.util.Properties;

 

import org.junit.Test;

 

public class jdbcUtils {
// 1、加载配置文件(只加载)
// 2、加载驱动类(只加载一次)
private static Properties props = null;
static {
try {
// 给props进行初始化,即加载dbconfig.properties文件到props对象中
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("dbconfig.properties");
props = new Properties();
props.load(in);
} catch(IOException e) {

}
// 2
try {
Class.forName(props.getProperty("driverClassName"));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
//在对程序进行操作时(增删改查操作)联系数据库的时候,只调用此方法即可
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(props.getProperty("url"), props
.getProperty("username"), props.getProperty("password"));
}

 

@Test
public void fun1() throws IOException, ClassNotFoundException, SQLException {
Connection con = jdbcUtils.getConnection();
System.out.println(con);
}
}

 

(二)数据库连接池

 

posted on 2015-08-24 16:12  脆皮软心  阅读(132)  评论(0)    收藏  举报