package com.qf.bmi.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 封装增删改方法
* @author 何洪玉
*
*/
public class JDBC_utils {
public static final String driver = "com.mysql.jdbc.Driver";
public static final String url = "jdbc:mysql://localhost:3306/bmi?useUnicode=true&characterEncoding=utf-8";
public static final String user = "root";
public static final String password = "";
static {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("获取驱动异常");
}
}
public static Connection getConnection() {
try {
return DriverManager.getConnection(url,user,password);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("获取连接异常");
}
}
public static int executeUpdate(String sql, Object...params) {
Connection connection = null;
PreparedStatement prepareStatement = null;
try {
connection = getConnection(); //获取连接
prepareStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
prepareStatement.setObject(i + 1, params[i]);
}
return prepareStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("操作异常");
}finally {
close(null, prepareStatement, connection);
}
}
public static void close(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {
if(resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("resultSet关闭异常");
}
}
if(preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("preparedStatement关闭异常");
}
}
if(connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("connection关闭异常");
}
}
}
}