我正在编写一个 Bukkit 插件,一个用于“我的世界”游戏的服务器。我不会写SQL,只是一些语法。
我正在寻找 Java 类来访问 MySQL 和 SQLite。该插件一次只使用一个数据库,在配置文件中设置,MySQL 或 SQLite。
我发现了这个:
import java.io.*;
import java.sql.*;
import java.util.logging.*;
import org.bukkit.plugin.*;
public class Db {
private final Plugin plugin;
private final String url;
private Logger log;
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;
public Db(final Plugin plugin, final String host, final String database,
final String user, final String password) {
this.plugin = plugin;
url = "jdbc:mysql://" + host + "/" + database + "?user=" + user
+ "&password=" + password;
log = plugin.getServer().getLogger();
initDriver("com.mysql.jdbc.Driver");
}
public Db(final Plugin plugin, final String filePath) {
this.plugin = plugin;
url = "jdbc:sqlite:" + new File(filePath).getAbsolutePath();
log = plugin.getServer().getLogger();
initDriver("org.sqlite.JDBC");
}
private void initDriver(final String driver) {
try {
Class.forName(driver);
} catch (final Exception e) {
log.severe("Database driver error:" + e.getMessage());
}
}
public int resultInt(ResultSet result, int column) {
if (result == null)
return 0;
try {
result.next();
int integer = result.getInt(column);
result.close();
return integer;
} catch (SQLException e) {
log.severe("Database result error: " + e.getMessage());
}
return 0;
}
public String resultString(ResultSet result, int column) {
if (result == null)
return null;
try {
result.next();
String string = result.getString(column);
result.close();
return string;
} catch (SQLException e) {
log.severe("Database result error: " + e.getMessage());
}
return null;
}
public ResultSet query(final String query) {
return query(query, false);
}
public ResultSet query(final String query, final boolean retry) {
try {
final Connection connection = DriverManager.getConnection(url);
final PreparedStatement statement = connection
.prepareStatement(query);
if (statement.execute())
return statement.getResultSet();
} catch (final SQLException e) {
final String msg = e.getMessage();
log.severe("Database query error: " + msg);
if (retry && msg.contains("_BUSY")) {
log.severe("Retrying query...");
plugin.getServer().getScheduler()
.scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
query(query);
}
}, 20);
}
}
return null;
}
}
但我不知道如何关闭连接和语句。在这段代码中,我必须使用
base = new Db(this, getDataFolder() + File.separator + "SQLite.db");
但是使用该代码会创建多个线程,这会给我带来错误。我必须找到一个可以关闭连接和语句的类。我只学习了几个星期的 Java,而且我知道的不多。