![](/img/trans.png)
[英]Java :How to connect to database using Jbutton taking user input data
[英]How do i write to a database by taking user input from a GUI and storing that user input into a database in java?
我最近一直在尝试通过从 GUI 获取用户输入来写入数据库,并且我想将来自 GUI 的用户输入存储在 netbeans 上的 derby 数据库中。 目前,我有一些代码,但它似乎不起作用,因为当我运行 GUI 并开始输入应该存储在数据库中我的程序后端的数据时,它不存储那个在 GUI 中输入的数据。 它不会将任何数据加载到数据库中!
这是写入数据库的代码:
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* @author Hammad
*/
public class WritePlayerDB
{
private final DBConnection dbc;
private final Connection conn;
private Statement stmt;
String insertQuery;
public WritePlayerDB()
{
dbc = new DBConnection();
conn = dbc.getConnection();
}
public void writeToPlayerDB()
{
try {
int playerID = 0;
insertQuery = "INSERT INTO 'PLAYERINFO' ('PLAYER_ID', 'PLAYER_NAME', 'PRIZE_WON', 'CORRECT_ANSWERS')" + "VALUES(1,2,3,4)";
this.stmt = conn.createStatement();
this.checkExistedTable("PLAYERS");
PreparedStatement ps = conn.prepareStatement(insertQuery);
CorrectAnswers.correctAnswers[MillionaireGui.moneyCounter] = PrizeMoney.prizeLadder[MillionaireGui.moneyCounter];
ps.setInt(1, playerID++);
ps.setString(2, MillionaireGui.nameField.getText());
ps.setInt(3, PrizeMoney.prizeLadder[MillionaireGui.moneyCounter]);
ps.setInt(4, CorrectAnswers.correctAnswers[MillionaireGui.moneyCounter]);
ps.executeUpdate();
ps.close();
}
catch (SQLException ex)
{
System.out.println(ex.getMessage());
}
}
public void checkExistedTable(String name)
{
try {
DatabaseMetaData dbmd = this.conn.getMetaData();
String[] types = {"TABLE"};
stmt = this.conn.createStatement();
ResultSet rs = dbmd.getTables(null, null, null, types);
while (rs.next()) {
String table_name = rs.getString("TABLE_NAME");
System.out.println(table_name);
if (table_name.equalsIgnoreCase(name)) {
stmt.executeUpdate("Drop table " + name);
System.out.println("Table " + name + " has been deleted.");
break;
}
}
rs.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
我正在为我的 GUI 的 JTextField 调用 actionListener 中的writeToPlayerDB()
方法,如下所示:
nameField.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (nameField.getText().equals(""))
{
blankName.setVisible(true);
blankName.setText("PLEASE DON'T LEAVE NAME BLANK");
}
else
{
playerName.setPlayerName(nameField.getText().toUpperCase());
WritePlayerDB wdb = new WritePlayerDB();
wdb.writeToPlayerDB();
blankNamePanel.setVisible(false);
introRuleScreen();
}
}
});
如果我能帮上忙,我将不胜感激,因为我已经坚持了很长时间!
没有足够的信息来真正了解您的核心问题是什么,但是...
static
不是一个好主意,尤其是当您处理 UI 元素时,因为您可能有多个 UI 实例,然后您无法再确定您实际引用的元素实例。 最好利用依赖注入并将信息直接传递给方法。
+ "VALUES(1,2,3,4)"
不是您使用PreparedStatement
的方式,有关详细信息,请参阅使用 Prepared Statements
还...
int playerID = 0;
//...
ps.setInt(1, playerID++);
表示玩家 id 始终为0
( ++
是后缀操作;首先赋值,然后添加)。 事实上,您应该不惜一切代价避免手动创建这样的记录 ID,并且数据库应该在内部使用“自动递增”值。 有关详细信息,请参阅自动生成的密钥。
为简单起见,我在以下示例中使用H2 数据库引擎。 否则它应该可以与 Derby 一起使用,但您需要删除createTables
方法
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.StringJoiner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.border.EmptyBorder;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
DatabaseManager db = new DatabaseManager();
db.open();
JFrame frame = new JFrame();
frame.add(new MainPane(db));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (SQLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
public class MainPane extends JPanel {
private JTextField nameField;
private JSpinner moneyCounter;
public MainPane(DatabaseManager database) {
setBorder(new EmptyBorder(32, 32, 32, 32));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_END;
gbc.insets = new Insets(4, 4, 4, 4);
add(new JLabel("Name: "), gbc);
gbc.gridy++;
add(new JLabel("Counter: "), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_START;
nameField = new JTextField(10);
moneyCounter = new JSpinner(new SpinnerNumberModel(0, 0, 100, 10));
add(nameField, gbc);
gbc.gridy++;
add(moneyCounter, gbc);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
if (name.isBlank()) {
JOptionPane.showMessageDialog(MainPane.this, "Name can not be blank", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
try {
int playerId = database.savePlayer(name, (int) moneyCounter.getValue());
List<String> results = database.getPlayerById(playerId);
StringJoiner sj = new StringJoiner("<br>", "<html>", "</html>");
for (String text : results) {
sj.add(text);
}
JOptionPane.showMessageDialog(MainPane.this, sj.toString(), "Success", JOptionPane.PLAIN_MESSAGE);
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(MainPane.this, "Failed to create player record", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
gbc.gridy++;
gbc.gridx = 0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.CENTER;
add(btnSave, gbc);
}
}
public class DatabaseManager {
private Connection connection;
protected void createTables() throws SQLException {
String cmd = "create table IF NOT EXISTS PLAYERINFO ("
+ "PLAYER_ID bigint GENERATED BY DEFAULT AS IDENTITY(START WITH 0) PRIMARY KEY,"
+ "PLAYER_NAME varchar(255) not null,"
+ "PRIZE_WON int not null,"
+ "CORRECT_ANSWERS int not null"
+ ")";
try (Statement stmt = connection.createStatement()) {
stmt.execute(cmd);
}
}
public void open() throws SQLException {
if (connection != null && !connection.isClosed()) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.WARNING, null, ex);
}
}
connection = DriverManager.getConnection("jdbc:h2:~/test");
createTables();
}
public void close() throws SQLException {
if (connection == null) {
return;
}
try {
if (connection.isClosed()) {
connection = null;
}
connection.close();
} finally {
connection = null;
}
}
public int savePlayer(String name, int counter) throws SQLException {
String cmd = "insert into PLAYERINFO (PLAYER_NAME, PRIZE_WON, CORRECT_ANSWERS) values (?, ?, ?)";
try (PreparedStatement stmt = connection.prepareStatement(cmd, Statement.RETURN_GENERATED_KEYS)) {
Random rnd = new Random();
stmt.setString(1, name);
stmt.setInt(2, rnd.nextInt(100) + 1);
stmt.setInt(3, counter);
if (stmt.executeUpdate() != 1) {
throw new SQLException("Unexpectedly modified more then one row");
}
try (ResultSet rs = stmt.getGeneratedKeys()) {
if (rs.next()) {
return rs.getInt(1);
}
}
}
throw new SQLException("Failed to create player record");
}
public List<String> getPlayerById(int id) throws SQLException {
String cmd = "select * from playerinfo where PLAYER_ID = ?";
List<String> results = new ArrayList<>(8);
try (PreparedStatement stmt = connection.prepareStatement(cmd)) {
stmt.setInt(1, id);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
String name = rs.getString("PLAYER_NAME");
int prizeWon = rs.getInt("PRIZE_WON");
int correctAnswer = rs.getInt("CORRECT_ANSWERS");
results.add(name + " won " + prizeWon + " with " + correctAnswer + " correct answers");
}
}
}
return results;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.