import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
/**
*
* @author xiaopihai
* @version 1.0
* @time 2014-12-28
*
*/
public class sqlHelper {
private final static String NAME="root";
private final static String PASSWORD="123456";
private final static String DRIVER="com.mysql.jdbc.Driver";
private final static String URL="jdbc:mysql://localhost:3306/DataBaseName";
private static Connection conn=null;
private static PreparedStatement pstmt=null;
private static ResultSet rs=null;
/**
* 连接数据库
* @return conn
*/
public static Connection getConnection(){
Connection conn=null;
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
System.out.println("注册驱动异常");
e.printStackTrace();
}
try {
conn=DriverManager.getConnection(URL, NAME, PASSWORD);
} catch (SQLException e) {
System.out.println("连接数据库异常");
e.printStackTrace();
}
return conn;
}
/**
* 一次性全部关闭
* @param conn
* @param pstmt
* @param rs
*/
public static void closeAll(Connection conn,PreparedStatement pstmt,ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pstmt!=null){
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 执行查询语句
* @param sql
* @param parameters
* @return rs
*/
public static ResultSet executeQuery(String sql,String[] parameters){
conn=getConnection();
try {
pstmt=conn.prepareStatement(sql);
if(parameters!=null && !sql.isEmpty()){
for(int i=0;i<parameters.length;i++){
pstmt.setString(i+1, parameters[i]);
}
}
rs=pstmt.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}finally{
closeAll(conn, pstmt, rs);
}
return rs;
}
/**
* 功能:执行更新操作
* @param sql
* @param parameters
*/
public static void excuteUpdate(String sql,String[] parameters){
conn=getConnection();
try {
pstmt=conn.prepareStatement(sql);
if(parameters!=null && !sql.isEmpty()){
for(int i=0;i<parameters.length;i++){
pstmt.setString(i+1, parameters[i]);
}
}
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally{
closeAll(conn, pstmt, rs);
}
}
}