方法层!
package poster.util;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.crypto.Data;
public class DBHelper {
private static final String url="jdbc:oracle:thin:@localhost:1521:orcl";
private static final String user="bbs";
private static final String password="123";
private static Connection con=null;
static{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch(ClassNotFoundException e){
e.printStackTrace();
}
try{
con=DriverManager.getConnection(url, user, password);
}catch(SQLException e){
e.printStackTrace();
}
}
/**
* 每次在操作數據之前都先獲取連接對象
* @throws SQLException
*/
public static void getConnection() throws SQLException{
con=DriverManager.getConnection(url, user, password);
}
/**
* @param sql
* @param objects
* @return 返回受影響的行數(針對的是增加,刪除,修改的操作)
* @throws SQLException
*/
public static int executeNonQuery(String sql,Object...objects) throws SQLException{
getConnection();
PreparedStatement pstm=con.prepareStatement(sql);
for(int i=0;i<objects.length;i++){
pstm.setObject(i+1, objects[i]);
}
int result=pstm.executeUpdate();
closeConnection();
return result;
}
/**
* @param sql
* @param objects
* @return 根據SQL語句獲取查詢的數據聚合
* @throws SQLException
*/
public static ResultSet executeQuery(String sql,Object...objects) throws SQLException{
getConnection();
PreparedStatement pstm=con.prepareStatement(sql);
for(int i=0;i<objects.length;i++){
pstm.setObject(i+1, objects[i]);
}
ResultSet set=pstm.executeQuery();
return set;
}
/**
* 每次用完連接之後就需要關閉
* @throws SQLException
*/
public static void closeConnection() throws SQLException{
if(con!=null){
con.close();
}
}
/**
* 时间
* @return
*/
public static String Csss(){
Date d=new Date();
SimpleDateFormat df=new SimpleDateFormat();
String s=df.format(d);
return s;
}
}