Home > Database > Mysql Tutorial > body text

Java JDBC使用配置文件连接数据库

WBOY
Release: 2016-06-07 17:34:40
Original
1280 people have browsed it

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

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 conns;
private Connection conn;


public JDBCFactory() throws Exception{
conns = new ArrayList();
prop = new Properties();
  //加载配置文件

prop.load(this.getClass().getResourceAsStream(CONFIGNAME));
  //获取数据库驱动

Class.forName(prop.getProperty("DRIVER_CLASS"));
  //创建十个数据库连接并放入List集合(conns),
  //list集合(conns)相当于一个有十个数据库连接的数据库连接池

for (int i = 0; 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"));
}
}
}

linux

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!