您的位置:首页 > 数据库 > Oracle

java通过配置文件jdbc.properties链接Oracle数据库工具类

2017-08-09 11:05 597 查看
package resources;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.Properties;

public class DbUtil {
public static Connection getConnection(){
String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null;

//读取类路径下的 jdbc.properties 文件,我的配置文件放在src包下
InputStream in = DbUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
try {
properties.load(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driverClass = properties.getProperty("driver");
jdbcUrl = properties.getProperty("jdbcUrl");
user = properties.getProperty("username");
password = properties.getProperty("password");

Driver driver = null;
try {
driver = (Driver) Class.forName(driverClass).newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Properties info = new Properties();
info.put("user", user);
info.put("password", password);

//通过 Driver 的 connect 方法获取数据库连接.
Connection connection = null;
try {
connection = driver.connect(jdbcUrl, info);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("----The database is connected----");
return connection;
}
}

jdbc.properties内容如下:
driver=oracle.jdbc.driver.OracleDriver
#jdbcUrl=jdbc\:oracle\:thin\:@10.91.4.102\:1521\:orcl
jdbcUrl=jdbc\:oracle\:thin\:@127.0.0.1\:1521\:orcl
username=cp2
password=cp2test

//调用方法
public static void main(String[] args) {
String id = "111111";
String gread = "3";
List<Student> sList = new ArrayList<Student>();
Connection con = DbUtilCR.getConnection();
PreparedStatement pre = null;
ResultSet result = null;
String sql = "select s.name,s.age from student s where s.id=? and s.gread=?";
try {
pre = con.prepareStatement(sql);
pre.setString(1, id);//传参数学号
pre.setString(2, gread);//传参数年级
result = pre.executeQuery();
System.out.println("执行SQL为:["+sql+"]");
System.out.println("参数为:["+id+","+gread+"]");
while (result.next()){
Student st = new Student();
st.setName(result.getString("name"));//与查询出的字段或者别名保持一致
st.setAge(result.getString("ag
4000
e"));
sList.add(st);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0;i<sList.size();i++) {
System.out.println("姓名:"+sList.get(i).getName()+"\t年龄:"+sList.get(i).getAge());

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息