admin管理员组文章数量:1389879
I am creating a system with MySQL and I can't seem to make it create a table and then insert the initial data for the users
table. It is connecting properly to the specified database but not creating table or insert the data.
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;
}
}
}
I keep getting this error:
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)
I am simply at lost and this is my first time trying out MySQL for a Java application.
I am creating a system with MySQL and I can't seem to make it create a table and then insert the initial data for the users
table. It is connecting properly to the specified database but not creating table or insert the data.
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;
}
}
}
I keep getting this error:
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)
I am simply at lost and this is my first time trying out MySQL for a Java application.
Share Improve this question asked Mar 14 at 13:22 Lourd Nathaniel GonzalezLourd Nathaniel Gonzalez 1612 silver badges11 bronze badges1 Answer
Reset to default 0Okay so I found the solution and it was just an error with the value I put in the setupTable() function specifically for the ResultSet. It should have been ResultSet tables = dbm.getTables(DB_URL, DB_Driver, tableName, null);
Apparently I used the Derby database approach which is different for MySQL.
本文标签: Java MySQL Could not create table and insert initial dataStack Overflow
版权声明:本文标题:Java MySQL: Could not create table and insert initial data - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744654391a2617877.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论