java mysql模板
Java mysql的模版,很优雅。同时也兼顾了性能PreparedStatement和安全性(防SQL注入)两方面。对于比较简单的数据库操作基本满足要求。
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import
java.sql.PreparedStatement;
import java.sql.ResultSet;
public class BaseDao {
public static final String DRIVER =
"oracle.jdbc.driver.OracleDriver";
public static final String URL =
"jdbc:oracle:thin:@localhost:1521:ORCL";
public static final String
USERNAME = "ma";
public static final String PASSWORD = "malei";
Connection connection = null;
PreparedStatement preparedStatement =
null;
ResultSet resultSet = null;
public Connection
getConnection() throws Exception {
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
return connection;
}
public ResultSet executeQuery(String sql)
throws Exception {
connection = this.getConnection();
preparedStatement = connection.prepareStatement(sql);
resultSet =
preparedStatement.executeQuery();
return resultSet;
}
public int executeUpdate(String sql,Object[] obj) throws Exception
{
connection = this.getConnection();
preparedStatement =
connection.prepareStatement(sql);
for(int i
=0;i<obj.length;i++){
preparedStatement.setObject(i+1,
obj[i]);
}
return preparedStatement.executeUpdate();
}
public void closeAll() throws Exception {
if(null !=
resultSet){
resultSet.close();
}
if(null !=
preparedStatement){
preparedStatement.close();
}
if(null != connection){
connection.close();
}
}
}