展开全部
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);
//通过e69da5e887aa3231313335323631343130323136353331333363383935 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\:orcljdbcUrl=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 sList = new ArrayList();
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(“age”));
sList.add(st);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0;i
System.out.println(“姓名:”+sList.get(i).getName()+”\t年龄:”+sList.get(i).getAge());
}
}