通过两种不同的方式进行读写数据,第一种是通过读取properties配置文件进行数据库的连接,第二种是直接在代码中进行数据库的连接!
第一种方法:
public void QueryTest() throws IOException {
//读取properties配置文件
Properties pro=new Properties();
FileInputStream in=new FileInputStream("././src/db.properties");
//将配置文件中的数据进行加载
pro.load(in);
driverName=pro.getProperty("driverName");
url=pro.getProperty("url");
user=pro.getProperty("user");
password=pro.getProperty("password");
PreparedStatement pstm=null;
ResultSet re=null;
Connection con=null;
try {
Class.forName(driverName);
con=DriverManager.getConnection(url,user,password);
String sql="select * from wh_admininfo where wh_adminid=?";
pstm=con.prepareStatement(sql);
//1代表的是占位符,从1开始,后边的为具体的值
pstm.setString(1,"1000");
//返回查询的结果
re=pstm.executeQuery();
if(re.next()){
String id=re.getString("wh_id");
String name=re.getString("wh_adminname");
String date=re.getString("wh_createddate");
String desc=re.getString("wh_admindesc");
String num=re.getString("wh_adminnumber");
String state=re.getString("wh_adminstate");
System.out.print(id+" "+name+" "+date+" "+
desc+" "+num+" "+state);
}else{
//输出查询结果
System.out.println("!");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
try{
if(re != null){
re.close();
}
if(pstm != null){
pstm.close();
}
if(con != null){
con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
第二种方法:
public void GetConnect(){
String driverName="oracle.jdbc.driver.OracleDriver";
String url="jdbc:oracle:thin:@localhost:1521:XE";
String user="system";
String password="0000";
PreparedStatement pstm=null;
ResultSet re=null;
Connection con=null;
try{
Class.forName(driverName);
con=DriverManager.getConnection(url, user, password);
System.out.println(con);
String sql = " select wh_id,wh_createddate,wh_adminname,wh_admindesc,wh_adminnumber,wh_adminstate from wh_admininfo where wh_adminid=?";
pstm=con.prepareStatement(sql);
pstm.setString(1,"1000");
re=pstm.executeQuery();
if(re.next()){
String id=re.getString("wh_id");
String name=re.getString("wh_adminname");
String date=re.getString("wh_createddate");
String desc=re.getString("wh_admindesc");
String num=re.getString("wh_adminnumber");
String state=re.getString("wh_adminstate");
System.out.print(id+" "+name+" "+date+" "+
desc+" "+num+" "+state);
}else{
//输出查询结果
System.out.println("!");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
try{
if(re != null){
re.close();
}
if(pstm != null){
pstm.close();
}
if(con != null){
con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}