java jdbc连接数据库,Properties 属性设置参数方法
今天在整合为数据库发现在配置中实现的赋值方式,可以用代码实现。特记录下共以后参考:
代码:
// 操作数据库
Connection conn;
String strDatabase ="northeasttycoon";
try {
String url = "jdbc:sqlserver:127.0.0.1:1433;DatabaseName=strDatabase;";
Properties pro = new Properties();
pro.setProperty("initialSize", "10");
pro.setProperty("maxActive", "100");
pro.setProperty("maxIdle", "70");
pro.setProperty("minIdle", "10");
pro.setProperty("testOnBorrow", "true");
pro.setProperty("validationQuery", "select 1");
pro.setProperty("removeAbandonedTimeout", "120");
pro.setProperty("removeAbandoned", "true");
pro.setProperty("username", strUserName);
pro.setProperty("password", strPassWord);
conn = DriverManager.getConnection(url, pro);
// Statement stmt;
PreparedStatement stmt;
ResultSet rs;
String sql = "select * from t_northeasttycoon";
// 建立Statement对象
stmt = conn.prepareStatement(sql);
/**
* Statement createStatement() 创建一个 Statement 对象来将 SQL 语句发送到(northeasttycoon)数据库。
*/
// 执行数据库查询语句
rs = stmt.executeQuery();
/**
* ResultSet executeQuery(String sql) throws SQLException 执行给定的
* SQL 语句,该语句返回单个 ResultSet 对象
*/
while (rs.next()) {
// 查询结果
}
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}