查增删改MySQL数据库固定模式
时间:2021-07-01 10:21:17
帮助过:2人阅读
public class Base {
public static Connection connection =
null;
public static PreparedStatement preparedStatement =
null;
public static ResultSet resultSet =
null;
public static int updateRows = 0
;
public Connection tomcatGetConnection() {
try {
Context context =
new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/mysql"
);
connection =
dataSource.getConnection();
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public ResultSet query(String sql, Object[] param) {
try {
preparedStatement =
connection.prepareStatement(sql);
for (
int i = 0; i < param.length; i++
) {
preparedStatement.setObject(i + 1
, param[i]);
}
resultSet =
preparedStatement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet;
}
public int update(String sql, Object[] param) {
try {
preparedStatement =
connection.prepareStatement(sql);
for (
int i = 0; i < param.length; i++
) {
preparedStatement.setObject(i + 1
, param[i]);
}
updateRows =
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return updateRows;
}
public void close() {
if (resultSet !=
null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement !=
null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection !=
null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
查增删改MySQL数据库固定模式
标签: