我是 java 的新手,几周前才开始接触。我有一项任务必须尽快完成。作业指出我必须为书店创建一个 JAVA 应用程序,允许用户使用适当的 GUI 执行数据库操作。
这个项目必须有 3 个类。一个用于 GETTERS 和 SETTERS,另一个用于 GUI 元素,最后一个用于 SQL 数据库准备语句。
提前,对于代码质量可能不佳,我深表歉意。
我的问题似乎是,当我运行项目并尝试更新或插入或删除时,它永远不会工作,而是弹出 JOPtionPane“数据未保存”。
如果有任何帮助、提示和建议,我将不胜感激。我项目的代码如下:
书本类( setter和getter ):
package bookDatabase;
public class Book {
String bookName; // Create Variable for the book name//
String authorName;
String price;
//We now create the setters and getters
public Book( String bookName, String authorName, String price){
this.bookName = bookName;
this.authorName = authorName;
this.price = price;
}
public void setbookName (String bookName ){
this.bookName = bookName;
}
public void setauthorName (String authorName){
this.authorName = authorName;
}
public void setprice (String price){
this.price = price;
}
public String getbookName(){
return bookName;
}
public String getauthorName (){
return authorName;
}
public String getprice (){
return price;
}
@Override
public String toString(){
return bookName + authorName + price ;
}
}
现在是 guiBook 类:
package bookDatabase;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
public class guiBook extends JFrame{
private String bookName;
private String authorName;
private String price;
Book b1 = new Book(bookName, authorName, price);
BookQuerie q1 = new BookQuerie(bookName, authorName, price);
private JTabbedPane pane = new JTabbedPane();
private JPanel panel1 = new JPanel();
private JTextArea areaShow= new JTextArea("List of All Books");
private JTable selectArea = new JTable();
private JPanel panel2 = new JPanel();
private JLabel update1 = new JLabel ("Insert Name of Book", JLabel.LEFT);
private JTextField updateField1 = new JTextField(20);
private JLabel update2 = new JLabel ("Enter the new Price", JLabel.LEFT);
private JTextField updateField2 = new JTextField(20);
private JButton updateButon = new JButton("Update price");
private JPanel panel3 = new JPanel();
private JTextField firstInsert = new JTextField(20);
private JTextField secondInsert = new JTextField(20);
private JTextField thirdInsert = new JTextField(20);
private JButton insertButton = new JButton("Insert New Book");
private JLabel labelInsert1 = new JLabel("Enter Book Name", JLabel.LEFT);
private JLabel labelInsert2 = new JLabel("Enter Author Name", JLabel.LEFT);
private JLabel labelInsert3 = new JLabel("Enter Price");
private JPanel panel4 = new JPanel();
private JTextField firstDelete = new JTextField(20);
private JButton buttonDelete = new JButton("Delete Book");
private JLabel labelDelete = new JLabel ( "Enter Name of Book", JLabel.LEFT);
public guiBook() throws Exception{
pane.add("Display All Books", panel1);
panel1.add(areaShow, BorderLayout.WEST);
areaShow.setEditable(false);
panel1.add(selectArea, BorderLayout.EAST);
{
pane.add("Update Book Price", panel2);
panel2.add(update1);
panel2.add(updateField1);
panel2.add(update2);
panel2.add(updateField2);
panel2.add(updateButon);
updateButon.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
String bookName = updateField1.getText();
String price = updateField2.getText();
try {
BookQuerie.updateBooks(bookName, price);
}
catch (SQLException e1) {
e1.printStackTrace();
}
}
});
pane.add("Insert New Book",panel3);
panel3.add(labelInsert1);
panel3.add(firstInsert);
panel3.add(labelInsert2);
panel3.add(secondInsert);
panel3.add(labelInsert3);
panel3.add(thirdInsert);
panel3.add(insertButton);
insertButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
String bookName = firstInsert.getText();
String authorName = secondInsert.getText();
String price = thirdInsert.getText();
try {
BookQuerie.insertBooks(bookName,authorName, price);
}
catch (SQLException e1) {
e1.printStackTrace();
}
}
});
pane.add("Delete Book", panel4);
panel4.add(labelDelete);
panel4.add(firstDelete);
panel4.add(buttonDelete);
buttonDelete.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
String bookName = firstDelete.getText();
try {
BookQuerie.deleteBooks(bookName);
}
catch (SQLException e1) {
e1.printStackTrace();
}
}
});
add(pane);
}
}
public static void main(String[] args) throws Exception{
guiBook app = new guiBook();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize(1000,400);
app.setVisible(true);
}
}
最后:BookQuerie 类:
package bookDatabase;
import java.sql.*;
import javax.swing.JOptionPane;
public class BookQuerie {
private static PreparedStatement selectAll;
private static PreparedStatement updateBook;
private static PreparedStatement insertBook;
private static PreparedStatement deleteBook;
private Connection connect;
private String bookName;
private static String authorName;
private static String price;
Book boooks = new Book(bookName, authorName, price);
public BookQuerie(String bookName, String authorName, String price) {
try{
connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookshop", "root", "");
selectAll = connect.prepareStatement("SELECT * FROM BOOK");
updateBook = connect.prepareStatement("UPDATE book SET price = ? WHERE bookName = ?");
insertBook = connect.prepareStatement("INSERT INTO book VALUES (?, ?, ?)");
deleteBook= connect.prepareStatement("DELETE FROM book WHERE bookName = ? ");
}
catch
(SQLException ex){
ex.printStackTrace();
}
}
public static String selectAll(String bookName, String authorName, String price) throws SQLException{
ResultSet rs = selectAll.executeQuery();
while(rs.next()){
rs.getString ("bookName");
rs.getString ("authorName");
rs.getString ("price");
}
return selectAll(bookName, authorName, price);
}
public static int updateBooks(String bookName, String price) throws SQLException{
updateBook.setString(1, bookName );
updateBook.setString(2, price);
int i = updateBook.executeUpdate();
if(i>0){
JOptionPane.showMessageDialog(null, "Data Is Saved!!");
System.exit(0);
}
else{
JOptionPane.showMessageDialog(null, "Data is Not Saved! :( " );
System.exit(0);
}
return updateBooks(bookName, price);
}
public static int insertBooks(String bookName, String authorName, String price) throws SQLException{
insertBook.setString(1, bookName);
insertBook.setString(2,authorName);
insertBook.setString(3, price);
int i = insertBook.executeUpdate();
if(i>0){
JOptionPane.showMessageDialog(null, "Data Is Saved!!");
}
else{
JOptionPane.showMessageDialog(null, "Data is Not Saved! :( " );
}
return insertBooks(bookName, authorName, price );
}
public static int deleteBooks (String bookName) throws SQLException{
deleteBook.setString(1, bookName);
return deleteBook.executeUpdate();
}
}
最佳答案
首先,您应该将“Book”类中的变量设为私有(private)。封装是一个关键的 OOP 概念。
您也可以尝试在插入语句中显式命名数据库列,例如:
String query = "insert into users (first_name, last_name, date_created, is_admin, num_points) values (?, ?, ?, ?, ?)";
其次在 guiBook 中(应该是 GuiBook 或 GUIBook 类名应该以大写字母开头)我会使用你创建的 Book 类。 根据您从文本字段中获得的值创建一个书籍对象,并将其传递给您的“插入”方法。
insertButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
String bookName = firstInsert.getText();
String authorName = secondInsert.getText();
String price = thirdInsert.getText();
Book book = new Book(bookName,authorName, price):
try {
BookQuerie.insertBooks(book);
}
catch (SQLException e1) {
e1.printStackTrace();
}
}
});
最后,我建议更改 BookQuerie (Query) 类,使其不在构造函数中创建所有准备好的语句。而是为您要完成的每个数据库操作创建一个单独的方法,例如:
public static boolean insertBook(Book book) throws SQLException{
PreparedStatement insertBook = null;
try(Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookshop", "root", "");){
insertBook = connect.prepareStatement("INSERT INTO book (NAME, AUTHOR, PRICE) VALUES (?, ?, ?)");
insertBook.setString(1, book.getName());
insertBook.setString(2,book.getAuthorName());
insertBook.setString(3, book.getPrice());
int i = insertBook.executeUpdate();
if(i>0){
JOptionPane.showMessageDialog(null, "Data Is Saved!!");
return true;
}
else{
JOptionPane.showMessageDialog(null, "Data is Not Saved! :( " );
return false;
}
catch
(SQLException ex){
ex.printStackTrace();
}
finally{
insertBook.close();
}
}
注意:在 try(Connection conn){} 中创建连接称为“使用资源尝试”,它从 Java 7 开始可用,并会在结束时自动关闭连接。
编辑
我从未提到过的一件事是您的方法会自行返回,例如
public static List<Book> selectAll() throws SQLException {
**return selectAll();**
}
这称为“递归”,可能会导致问题。在你的代码中它不应该存在。
关于您的 selectAll() 方法,您从数据库中选择了多条记录,因此需要将这些记录存储在某种列表中。例如:
public static List<Book> selectAll() throws SQLException {
PreparedStatement ps = null;
ResultSet rs = null;
// THE LIST OF BOOKS YOU WILL RETURN
List<Book> books = new ArrayList<>();
String sql = "SELECT NAME, AUTHOR, PRICE FROM BOOK";
try(Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookshop", "root", "");){
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
String name = rs.getString ("NAME");
String author = rs.getString ("AUTHOR");
String price = rs.getString ("PRICE");
// CREATE NEW BOOK WITH EACH ROW FROM RESULTSET
Book book = new Book( name, author, price);
// ADD BOOK TO THE LIST
books.add(book);
}
}
finally{
ps.close();
rs.close();
}
// RETURN LIST OF ALL BOOKS
return books;
}
然后在您的 GuiBook 类中,您可以创建另一个使用 selectAll() 方法填充您的 Jpanel 的方法,例如:
private void populateJPanel(){
// GET LIST OF ALL BOOKS (selectAll() throws sql exception so we handle it here.)
List<Book> books = null;
try {
books = BookQuery.selectAll();
} catch (SQLException e) {
e.printStackTrace();
}
// LOOP THROUGH BOOK LIST
for (Book book : books) {
String name = book.getName();
String author = book.getAuthor();
String price = book.getPrice();
// NOW USE THESE VALUES HOWEVER YOU PLEASE ON YOUR JPANEL
}
}
希望这有助于...
关于Java SQL 应用程序。输入没有更新到我的数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45031595/