java jdbc使用配置文件连接数据库:

java jdbc使用配置文件连接数据库:

创建后缀名为:.properties的文件,文件内容包括,数据库驱动、连接的数据库地址、用户名、密码……

以Mysql为例创建config.properties配置文件其内容如下:

DRIVER_CLASS=com.mysql.jdbc.Driver

CONNECTION_URL=jdbc:mysql://localhost:3306/test

CONNECTION_USERNAME=root

CONNECTION_PASSWORD=root

 

创建连接数据库类:

例如:

 

public class ConnectionFactory {

 

 

private static Properties prop;

private static final String CONFIGNAME = "config.properties";

private static List<Connection> conns;

private Connection conn;

 

public JDBCFactory() throws Exception{

conns = new ArrayList<Connection>();

prop = new Properties();

   //加载配置文件

prop.load(this.getClass().getResourceAsStream(CONFIGNAME));

   //获取数据库驱动

Class.forName(prop.getProperty("DRIVER_CLASS"));

   //创建十个数据库连接并放入List集合(conns),

   //list集合(conns)相当于一个有十个数据库连接的数据库连接池

for (int i = 0; i < 10; i++) {

conn = DriverManager.getConnection(

prop.getProperty("CONNECTION_URL"),

prop.getProperty("CONNECTION_USERNAME"),

prop.getProperty("CONNECTION_PASSWORD"));

conns.add(conn);

}

}

//从List集合(conns)中获取数据库连接

 

public Connection getConnection(){

   return conns.remove(0);

}

//已用完的数据库连接从新添加到List集合(conns)中

public void close(Connection conn){

if(conn!=null){

conns.add(conn);

}

}

}

定义测试类:

public class JDBCTest {

public static void main(String[] args) throws Exception {

   //创建ConnectionFactory对象,同时创建数据库连接池

ConnectionFactory cf = new ConnectionFactory();

   //获取数据库连接

Connection conn = cf.getConnection();

   //select sql语句

PreparedStatement ps = conn.prepareStatement("select * from user");

   //执行sql语句

ResultSet rs = ps.executeQuery();

   //循环输入查询到的内容

while(rs.next()){

       //id username password 为查询数据库的字段

System.out.println("id:"+rs.getInt("id")+

"Username:"+rs.getString("username")+

"Password:"+rs.getString("password"));

}

}

}

posted on 2014-01-18 12:40  劃破手  阅读(10585)  评论(1编辑  收藏  举报

导航