我是java的新手,几周前才开始。我的作业很快就要完成了。该任务规定我必须为书店创建一个JAVA应用程序,允许用户使用适当的GUI执行数据库操作。
这个项目必须有3个班级。一个用于GETTERS和SETTERS另一个用于GUI元素,最后一个用于SQL DATABASE PREPARED STATEMENTS。
提前知道,我为可能代码质量不好而道歉。我的问题似乎是,当我运行项目并尝试更新或插入或删除时,它永远不会工作,而是弹出JOPtionPane“数据未保存”。
我真的很感激任何帮助,提示,建议。我的项目代码如下:
预订课程(GETTERS AND SETTERS):
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();
}
}
答案 0 :(得分:1)
首先,您应该将“Book”类中的变量设为私有。封装是一个关键的OOP概念。
您可以尝试在insert语句中明确命名数据库列,例如:
字符串查询=“插入用户(first_name,last_name,date_created,is_admin,num_points)值(?,?,?,?,?)”;
其次在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){}中创建连接称为“try with resources”,它可以从java 7开始提供,并在最后自动关闭连接。
修改强>
我从未提及过的一件事就是你的方法会自行回归,例如。
public static List<Book> selectAll() throws SQLException {
**return selectAll();**
}
这称为“递归”,可能会导致问题。在你的代码中它不应该在那里。
关于selectAll()方法,您从DB中选择多条记录,因此需要将这些记录存储在某种列表中。 e.g:
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
}
}
希望这会有所帮助......