import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Jdbc {
private static Jdbc instance;
private Connection conn;
private PreparedStatement statement;
private ResultSet resultSet;
private Jdbc() {
try {
// 加载驱动
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Jdbc getInstace() {
if (instance == null) {
instance = new Jdbc();
}
return instance;
}
private void createConnection() {
try {
// 判断数据库连接如果是空或者已经关闭,就重写创建
if (conn == null || conn.isClosed()) {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/xxxx", "root", "root");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean executeUpdate(String sql, Object... objects) throws SQLException {
this.createStatement(sql, objects);
//执行sql
boolean result = statement.executeUpdate() > 0;
//释放资源
this.release();
return result;
}
public Map executeQuery(String sql, Object... objects) throws SQLException{
this.createStatement(sql, objects);
resultSet = statement.executeQuery();
Map row = null;
if(resultSet.next()){
row = new HashMap<>();
ResultSetMetaData meta = resultSet.getMetaData();
for (int i = 1; i <= meta.getColumnCount(); i++) {
String lable = meta.getColumnName(i);
row.put(lable, resultSet.getObject(lable));
}
}
return row;
}
public List
private void release() {
try {
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}