//方法一;
package DBUtils;
import java.io.InputStream;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
public class DBUtils {
private static String DriverClass;
private static String url;
private static String username;
private static String password;
private static BasicDataSource dataSource = new BasicDataSource();
static {
loadRead();
dataSource.setDriverClassName(DriverClass);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
}
private static void loadRead() {
try {
InputStream in = DBUtils.class.getClassLoader()
.getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(in);
DriverClass = properties.getProperty("DriverClass");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
} catch (Exception e) {
e.printStackTrace();
}
}
public static DataSource getDataSource(){
return dataSource;
}
}
//方法二:
package DBCPUtils;
import java.util.List;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
public class DBCPUtils {
public static void main(String[] args) {
try {
// 读取配置文件
Properties properties = new Properties();
properties.load(DBCPUtils.class.getClassLoader()
.getResourceAsStream("jdbc.properties"));
// 从连接池中获取连接对象
DataSource dataSource = BasicDataSourceFactory
.createDataSource(properties);
String sql = "select * from emp";
QueryRunner qr = new QueryRunner(dataSource);
List<Object[]> list = qr.query(sql, new ArrayListHandler());
for (Object[] objects : list) {
for (Object object : objects) {
System.out.print(object + "\t");
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
|