import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCUtil {
private static String driverClassName = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/mydb";
private static String username = "root";
private static String password = "root";
static {
try {
Class.forName(driverClassName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
Connection connection = DriverManager.getConnection(url, username, password);
return connection;
}
public static void closeConnection(Connection connection) throws SQLException {
connection.close();
}
public static int executuUpdate(String sql,Object[] params) throws SQLException {
Connection connection = getConnection();
PreparedStatement s = connection.prepareStatement(sql);
if(params != null) {
for(int i=0;i<params.length;i++) {
s.setObject(i+1, params[i]);
}
}
int n = s.executeUpdate();
s.close();
connection.close();
return n;
}
public static ResultSet executuQuery(Connection connection,String sql,Object[] params) throws SQLException {
PreparedStatement s = connection.prepareStatement(sql);
if(params != null) {
for(int i=0;i<params.length;i++) {
s.setObject(i+1, params[i]);
}
}
ResultSet n = s.executeQuery();
return n;
}
}
JDBC工具
最新推荐文章于 2022-03-08 09:22:46 发布