java mysql:无法创建表并插入初始数据

问题描述 投票:0回答:0
package lngtech.database; import java.lang.reflect.InvocationTargetException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.*; import java.util.Base64; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; public final class DatabaseHandler { private static DatabaseHandler handler; private final String DB_Driver = "com.mysql.cj.jdbc.Driver"; private final String DB_URL = "jdbc:mysql://localhost:3306/inventory_system?zeroDateTimeBehavior=CONVERT_TO_NULL"; private static Connection conn = null; private static Statement stmt = null; private static PreparedStatement pst = null; private static final Logger logger = Logger.getLogger(DatabaseHandler.class.getName()); public DatabaseHandler() { createConnection(); setupTables(); populateUsersTable(); } public static synchronized DatabaseHandler getInstance() { if (handler == null) { handler = new DatabaseHandler(); } return handler; } private void createConnection() { try { Class.forName(DB_Driver).getDeclaredConstructor().newInstance(); conn = DriverManager.getConnection(DB_URL, "root", "myDbPassword"); } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InstantiationException | NoSuchMethodException | SecurityException | InvocationTargetException | SQLException e) { logger.log(Level.SEVERE, "Failed to create database connection", e); } } public void closeConnection() { if (conn != null) { try { conn.close(); } catch (SQLException e) { logger.log(Level.SEVERE, "Error closing connection", e); } } } private void setupTables() { setupUsersTable(); } void setupTable(String tableName, String createStatement) { try { stmt = conn.createStatement(); DatabaseMetaData dbm = conn.getMetaData(); ResultSet tables = dbm.getTables(null, null, tableName, null); if (!tables.next()) { stmt.execute(createStatement); } } catch (SQLException e) { System.err.println(e.getMessage() + " ... setupDatabase"); } } void setupUsersTable() { String createTable = """ CREATE TABLE IF NOT EXISTS users ( id VARCHAR(255) PRIMARY KEY NOT NULL, firstName VARCHAR(255) NOT NULL, lastName VARCHAR(255) NOT NULL, email VARCHAR(255) UNIQUE NOT NULL, username VARCHAR(255) UNIQUE NOT NULL, password VARCHAR(255) NOT NULL, isActive BOOLEAN DEFAULT TRUE NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL, deleted_at TIMESTAMP NULL DEFAULT NULL ) """; setupTable("users", createTable); } private void populateUsersTable() { String userId = UUID.randomUUID().toString(); String firstName = "John Smith"; String lastName = "Doe"; String email = "[email protected]"; String username = "lngtech"; String password = hashPassword("S@mpl3P@s$w0rD"); String insertData = "INSERT INTO users (id, firstName, lastName, email, username, password) VALUES ('" + userId + "', '" + firstName + "', '" + lastName + "', '" + email + "', '" + username + "', '" + password + "')"; execAction(insertData); } private String hashPassword(String password) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hashedBytes = digest.digest(password.getBytes()); return Base64.getEncoder().encodeToString(hashedBytes); } catch (NoSuchAlgorithmException e) { logger.log(Level.SEVERE, "Error hashing password", e); return null; } } public ResultSet execQuery(String query) { try { stmt = conn.createStatement(); return stmt.executeQuery(query); } catch (SQLException e) { logger.log(Level.SEVERE, "Error executing query: " + query, e); return null; } } public boolean execAction(String qu) { try { stmt = conn.createStatement(); stmt.execute(qu); return true; } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error: " + e.getMessage(), "Error occured", JOptionPane.ERROR_MESSAGE); logger.log(Level.SEVERE, "Error executing action: " + qu, e); return false; } } public boolean execUpdate(String qu, Object... params) { try { pst = conn.prepareStatement(qu); for (int i = 0; i < params.length; i++) { pst.setObject(i + 1, params[i]); } pst.executeUpdate(); return true; } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error: " + e.getMessage(), "Error occured", JOptionPane.ERROR_MESSAGE); logger.log(Level.SEVERE, "Error executing update: " + qu, e); return false; } } }

我继续遇到此错误:

run: Mar 14, 2025 9:16:43 PM lngtech.database.DatabaseHandler execAction SEVERE: Error executing action: INSERT INTO users (id, firstName, lastName, email, username, password) VALUES ('ad0186e4-bfdf-4710-b437-8c1c42d9fde5', 'John Smith', 'Doe', '[email protected]', 'lngtech', 'qrAHYe/qRPJW5pN8YXSxBI9mmlsiWDbhwUtVT9xcxts=') java.sql.SQLSyntaxErrorException: Table 'inventory_system.users' doesn't exist at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:112) at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:114) at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:837) at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:685) at lngtech.database.DatabaseHandler.execAction(DatabaseHandler.java:133) at lngtech.database.DatabaseHandler.populateUsersTable(DatabaseHandler.java:105) at lngtech.database.DatabaseHandler.<init>(DatabaseHandler.java:29) at lngtech.database.DatabaseHandler.getInstance(DatabaseHandler.java:34) at lngtech.app.SplashScreen$DatabaseConnectionThread.run(SplashScreen.java:41) BUILD SUCCESSFUL (total time: 1 minute 4 seconds) 我只是在Lost,这是我第一次尝试MySQL来使用Java应用程序。 Error: Table 'inventory_system.users' doesn't exist

okay因此我找到了解决方案,这只是我在setuptable()函数中专门用于结果集中的值的错误。应该是
ResultSet tables = dbm.getTables(DB_URL, DB_Driver, tableName, null);
显然我使用了Derby数据库方法,该方法对MySQL有所不同。

java mysql
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.