AuLiveCodeMysql/src/main/java/com/yaohun/aulivecode/util/SqlUtil.java
2024-07-16 22:58:42 +08:00

103 lines
2.9 KiB
Java

package com.yaohun.aulivecode.util;
import com.yaohun.aulivecode.database.MegumiSQL;
import java.sql.*;
public class SqlUtil extends MegumiSQL {
private final String hostname;
private final String port;
private final String database;
private final String username;
private final String password;
private Connection connection;
public SqlUtil(String hostname, String port, String database, String username, String password) {
this.hostname = hostname;
this.port = port;
this.database = database;
this.username = username;
this.password = password;
this.connection = null;
}
@Override
public void openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
this.connection = DriverManager.getConnection("jdbc:mysql://" + this.hostname + ":" + this.port + "/" + this.database + "?useSSL=false", this.username, this.password);
} catch (SQLException e) {
System.out.println("[日志 - 错误] 连接数据库失败!");
this.connection = null;
} catch (ClassNotFoundException e) {
System.out.println("[日志 - 错误] 未找到JDBC驱动程序");
this.connection = null;
}
}
@Override
public boolean checkConnection() {
return this.connection != null;
}
@Override
public Connection getConnection() {
return this.connection;
}
@Override
public void closeConnection() {
if (this.connection != null) {
try {
this.connection.close();
this.connection = null;
} catch (SQLException e) {
System.out.println("[日志 - 错误] 关闭数据库连接失败!");
e.printStackTrace();
}
}
}
public ResultSet querySQL(String query) {
Connection conn;
if (checkConnection())
conn = getConnection();
else
return null;
Statement stat = null;
try {
stat = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
ResultSet result = null;
try {
if (stat != null)
result = stat.executeQuery(query);
else
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
return result;
}
public boolean updateSQL(String data) {
Connection conn;
if (checkConnection())
conn = getConnection();
else
return false;
Statement stat = null;
try {
stat = conn.createStatement();
stat.executeUpdate(data);
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}