本文采用了双重校验的方式封装了mysql数据库,需要的可以按需添加修改
public class JDBC {
private volatile static JDBC jdbc;
private String UTR = "jdbc:mysql://127.0.0.1:3306/huashy?useSSL=false&serverTimezone=UTC&characterEncoding=UTF8";//
private String NAME = "root";
private String PASSWORD = "root";
private Connection coon=null;
private Statement statement = null;
private ResultSet resultSet = null;
private JDBC(){}
/**
* 获取JDBC对象,单列模式(双重校验)
* @return
*/
public static JDBC getJDBC() {
if (jdbc == null) {
synchronized (JDBC.class) {
if (jdbc == null) {
jdbc = new JDBC();
}
}
}
return jdbc;
}
public void setData(String UTR,String NAME,String PASSWORD) {
this.UTR = UTR;
this.NAME = NAME;
this.PASSWORD = PASSWORD;
}
/**
* 创建数据库连接
*/
public void connection(){
try {
Class.forName("com.mysql.cj.jdbc.Driver");//加载驱动
coon = DriverManager.getConnection(UTR, NAME, PASSWORD);//创建连接对象
statement = coon.createStatement();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 新增一条数据
* 返回值i用于判断新增操作是否成功
*/
public int addData(String sql){
int i = 0;
try {
i=statement.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
close();
return i;
}
/**
* 关闭连接
*/
public void close(){
try {
if (statement!=null){
statement.close();
}
if (resultSet!=null){
resultSet.close();
}
if (coon!=null){
coon.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}