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;
/**
* Connect to Database
* @return Conn
*/
public static Connection getconnection () {
Connection Conn=null;
try {
Class.forName (DRIVER);
} catch (ClassNotFoundException e) {
SYSTEM.OUT.PRINTLN ("Registration driver exception");
E.printstacktrace ();
}
try {
Conn=drivermanager.getconnection (URL, NAME, PASSWORD);
} catch (SQLException e) {
SYSTEM.OUT.PRINTLN ("Connection Database Exception");
E.printstacktrace ();
}
Return conn;
}
/**
* All at once all closed
* @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 ();
}
}
}
/**
* Execute Query statement
* @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;
}
/**
* Function: Perform update operation
* @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);
}
}
}
Self-encapsulated SqlHelper code