Bukkit 1.20 Java 数据库表格:含 BOOLEAN 列
要使用 Java 编写一个 Bukkit 1.20 版本的含有 BOOLEAN 列的数据库表格,你可以使用以下代码示例:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BooleanTable {
private Connection connection;
private String tableName;
public BooleanTable(String tableName) {
this.tableName = tableName;
}
public void connect(String host, int port, String database, String username, String password) throws SQLException {
String url = 'jdbc:mysql://' + host + ':' + port + '/' + database + '?useSSL=false';
connection = DriverManager.getConnection(url, username, password);
}
public void createTable() throws SQLException {
String query = 'CREATE TABLE IF NOT EXISTS ' + tableName + ' (id INT AUTO_INCREMENT PRIMARY KEY, value BOOLEAN)';
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.executeUpdate();
}
}
public void insertData(boolean value) throws SQLException {
String query = 'INSERT INTO ' + tableName + ' (value) VALUES (?)';
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setBoolean(1, value);
statement.executeUpdate();
}
}
public void retrieveData() throws SQLException {
String query = 'SELECT * FROM ' + tableName;
try (PreparedStatement statement = connection.prepareStatement(query)) {
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
int id = resultSet.getInt('id');
boolean value = resultSet.getBoolean('value');
System.out.println('ID: ' + id + ', Value: ' + value);
}
}
}
public void disconnect() throws SQLException {
if (connection != null) {
connection.close();
}
}
public static void main(String[] args) {
BooleanTable booleanTable = new BooleanTable('my_table');
try {
booleanTable.connect('localhost', 3306, 'my_database', 'username', 'password');
booleanTable.createTable();
booleanTable.insertData(true);
booleanTable.insertData(false);
booleanTable.retrieveData();
booleanTable.disconnect();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
在上述代码中,我们创建了一个名为'BooleanTable'的类,它包含了连接到数据库、创建表格、插入数据和检索数据的方法。在'main'方法中,我们创建了一个'BooleanTable'对象,并使用相应的数据库信息进行连接。然后,我们创建了一个名为'my_table'的表格,并插入了一个'true'值和一个'false'值。最后,我们检索并打印了表格中的数据。
请注意,你需要将代码中的'host'、'port'、'database'、'username'和'password'替换为你实际使用的数据库连接信息。此外,你还需要将'my_table'替换为你想要的表格名称。
原文地址: https://www.cveoy.top/t/topic/fSIL 著作权归作者所有。请勿转载和采集!