public static Connection getConn(){
Connection conn = null;
String driverclass = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
String url = "jdbc:microsoft:sqlserver://localhost:1433;databasename=webstore";
String user = "sa";
String password = "";
try {
Class.forName(driverclass);
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
try {
conn = DriverManager.getConnection(url, user, password);
}
catch (SQLException ex1) {
ex1.printStackTrace();
} return conn;
} /**
* 关闭数据库资源
* @param rs ResultSet
* @param st Statement
* @param conn Connection
*/
public static void tryCloseDB(ResultSet rs,Statement st,Connection conn){ if (rs != null){ try {
rs.close();
}
catch (SQLException ex) {
}
} if(st != null){ try {
st.close();
}
catch (SQLException ex1) {
}
} if(conn != null){ try {
conn.close();
}
catch (SQLException ex2) {
}
} } /**
* 执行数据库的增、删、改操作
* @param sql String
* @return boolean
*/
public static boolean executeSql(String sql){ Connection conn = getConn();
Statement st = null;
int i = -1;
try {
st = conn.createStatement();
i = st.executeUpdate(sql);
}
catch (SQLException ex) {
}finally{ tryCloseDB(null,st,conn);
}
if (i>0){
return true;
}else{
return false;
}
} }要用到static?
Connection conn = null;
String driverclass = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
String url = "jdbc:microsoft:sqlserver://localhost:1433;databasename=webstore";
String user = "sa";
String password = "";
try {
Class.forName(driverclass);
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
try {
conn = DriverManager.getConnection(url, user, password);
}
catch (SQLException ex1) {
ex1.printStackTrace();
} return conn;
} /**
* 关闭数据库资源
* @param rs ResultSet
* @param st Statement
* @param conn Connection
*/
public static void tryCloseDB(ResultSet rs,Statement st,Connection conn){ if (rs != null){ try {
rs.close();
}
catch (SQLException ex) {
}
} if(st != null){ try {
st.close();
}
catch (SQLException ex1) {
}
} if(conn != null){ try {
conn.close();
}
catch (SQLException ex2) {
}
} } /**
* 执行数据库的增、删、改操作
* @param sql String
* @return boolean
*/
public static boolean executeSql(String sql){ Connection conn = getConn();
Statement st = null;
int i = -1;
try {
st = conn.createStatement();
i = st.executeUpdate(sql);
}
catch (SQLException ex) {
}finally{ tryCloseDB(null,st,conn);
}
if (i>0){
return true;
}else{
return false;
}
} }要用到static?
不用 new 类()
性能方面没有研究过