我正在我的图书馆管理系统项目中实施搜索图书框架。在这个框架中,我想检查这本书的可用性。我有两个数据库表:
1本书: - 保存图书馆中所有图书的记录 2本发行书; - 保留已发行书籍的记录
当我运行框架时,public void actionPerformed(ActionEvent e) {
String bookname=tfBookName.getText();
int count=0;
try{
con=DemoConnection.getConnection();
ps=con.prepareStatement("select book.bookid from book,issuebook where book.bookid!=issuebook.bookid and bookname=?");
ps.setString(1, bookname);
rs=ps.executeQuery();
while(rs.next())
{
count++;
String bookid =rs.getString(1);
String availability="Available";
Object[] row = { bookid, bookname, availability};
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.insertRow(0,row);
}
ps1=con.prepareStatement("select book.bookid from book,issuebook where book.bookid=issuebook.bookid and bookname=?");
ps1.setString(1, bookname);
rs1=ps1.executeQuery();
while(rs1.next())
{
String bookid =rs1.getString(1);
String availability="Issued";
Object[] row = { bookid, bookname, availability};
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.insertRow(0,row);
}
if(rs==null&&rs1==null)
{
JOptionPane.showMessageDialog(frame, "Book named"+bookname+"does not exist!!");
}
else if(rs==null&&rs!=null)
{
JOptionPane.showMessageDialog(frame, "All the copies of"+bookname+" book are issued!!");
}
else if(rs!=null&&rs==null)
{
JOptionPane.showMessageDialog(frame, "All the copies of"+bookname+" book are avaialble!!");
}
else if(rs!=null&&rs!=null)
{
JOptionPane.showMessageDialog(frame, count+" copies of"+bookname+" book is avaliable!!");
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
});
将填充相同的值三次。输出附加在代码之后。我无法找到问题所在。这是我的代码:
sh ./script.sh
这里的输出。发行的书,如表所示;没有重复的条目被填满,但是重复的条目填写在可用书籍的表格中。
答案 0 :(得分:0)
As @Blip stood out, the problem lies in your SQL query, especially the first one
select book.bookid from book,issuebook where book.bookid!=issuebook.bookid and bookname=?
In this query, you get the book.bookid each time it is different from an issuebook.bookid. So as you have 3 records in your issuebook table, you get 3 results when a book is not present in this table. Directly trying this query on your console should point this out.
The solution can be to modify your query as
select book.bookid, IF(issuebook.bookid IS NULL, 'Available', 'Issued') as availability from book,issuebook where LEFT JOIN availability ON (book.bookid, issuebook.bookid) and bookname=?
I'm not very used to MySQL and the "LEFT JOIN" notation, but the idea is to automatically get the availability status depending on weither or not the bookid is present in the issuebook table or not. So maybe there is some syntax flaws in my sample query...
Anyway like this you just have to do ONE SQL query (get rid of this ps1, res1...) and get the availability with
String availability=rs.getString(2);
If you are not familiar with SQL JOIN, I advise to document yourself on the subject :).
Hope this will help ;)