我正在为一个学校项目制作一个图书馆系统。在我的搜索功能中,我有一个SQL查询,它被输出到一个结果集中,然后用来创建一个DefaultTableModel,而DefaultTableModel又被用来更新表并显示搜索结果。
这个搜索的代码如下。
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
public class Search
{
private final String searchTerm, fileDir, table, defOrder;
private String condition;
private final String [] bookColumnNames;
private final boolean showLoaned, showDistinct;
public Search(String term, String dir, String tbl, String order, boolean showLoan, boolean distinct)
{
this.bookColumnNames = new String[]{"Title", "Author", "Genre", "ISBN", "Checkout"};
searchTerm = term;
fileDir = dir;
table = tbl;
showLoaned = showLoan;
showDistinct = !distinct;
defOrder = order;
}
DefaultTableModel searchBooks()
{
DefaultTableModel res = new DefaultTableModel();
for (String columnName : bookColumnNames)
{
res.addColumn(columnName);
}
if(isISBN(searchTerm))condition = "ISBN LIKE '" + searchTerm + "*'";
else if(showLoaned)condition = "Title LIKE '" + searchTerm + "*' OR Author LIKE '" + searchTerm + "*' OR Genre LIKE '" + searchTerm + "*'";
else condition = "(Title LIKE '" + searchTerm + "*' OR Author LIKE '" + searchTerm + "*' OR Genre LIKE '" + searchTerm + "*') AND Loaned = No";
String defaultQuery;
if(showDistinct) defaultQuery = "SELECT DISTINCT Title, Author, Genre, ISBN from " + table + " WHERE " + condition + " " + defOrder + ";";
else defaultQuery = "SELECT Title, Author, Genre, ISBN from " + table + " WHERE " + condition + " " + defOrder + ";";
ResultSet resSet = search(defaultQuery);
int columns = 4;
try
{
while (resSet.next())
{
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++)
{
row[i - 1] = resSet.getObject(i);
}
res.insertRow(resSet.getRow()-1,row);
}
}
catch(SQLException e)
{
}
return res;
}
ResultSet search(String defQuery)
{
ResultSet res = null;
try
{
Connection connection = DriverManager.getConnection("jdbc:ucanaccess://" + fileDir);
PreparedStatement prepState = connection.prepareStatement(defQuery);
res = prepState.executeQuery();
}
catch(SQLException e)
{
System.out.println(e);
}
return res;
}
private boolean isISBN(String term)
{
boolean check = true;
if(term.length() == 13)
{
for(int i = 1; i <= term.length(); i++)
{
if(!Character.isDigit(term.charAt(i - 1)))
{
check = false;
break;
}
}
}
else
{
check = false;
}
return check;
}
更新表格的代码在这里
private void searchBarButtonActionPerformed(java.awt.event.ActionEvent evt)
{
search = new Search(searchBar.getText(), config.get("databaseFileDirectory"),"tblBooks", config.get("defaultBookSort"), showLoaned.isSelected(), showDistinct.isSelected());
DefaultTableModel model = search.searchBooks();
searchResults.setModel(model);
numSearchResults.setText(model.getRowCount() + " result(s) found");
}
有没有办法在表的最后一列放置一个按钮checkbox,取决于书是否被借出?如果有,我如何使这个按钮的功能能够让我将该特定的表项添加到二维对象数组或列表中,以创建一个购物车?这个按钮checkbox应该放在 "结账 "栏中。
如果我的方法效率不高,我确实很抱歉。我从事Java开发只有1.5年左右,这是我的第一个大项目。任何关于逻辑解决方案或实际代码方面的建议都将受到极大的感激。
我正在为一个学校项目制作一个库系统。
当处理一个大型的Java应用程序时,一个简化编码的方法是使用一个 模型视图控制器 模式。 通过分离关注点,你可以一次专注于应用程序的一个部分。
好了,我要做一些假设。 让我们假设一个图书馆有书。
所以,让我们创建一个类来存放一本书。 这个类是一个普通的Java类。 它与Swing或任何类型的GUI没有任何关系。 它是完全独立的。 我们称之为模型类。
这个类是应用模型的一部分。 还会有其他类来描述一个库的其他方面。
import java.util.ArrayList;
import java.util.List;
public class Book {
private final String title;
private final String isbn;
private List<String> author;
private List<String> genre;
public Book(String title, String isbn) {
this.title = title;
this.isbn = isbn;
this.author = new ArrayList<>();
this.genre = new ArrayList<>();
}
public String getTitle() {
return title;
}
public void addAuthor(String author) {
this.author.add(author);
}
public List<String> getAuthor() {
return author;
}
public String getIsbn() {
return isbn;
}
public void addGenre(String genre) {
this.genre.add(genre);
}
public List<String> getGenre() {
return genre;
}
}
在Java中,类名是TitleCase。 方法名和字段名是camelCase。
所有在 Book
类与一本书有关。 为了拥有一个书的集合,我们将创建一个叫做 List<Book>
在不同的模式类中。
一本书只有一个标题。 它可以有一个副标题,但我选择不包含副标题字段。 如果你愿意,你可以添加一个副标题字段。
一本书有一个或多个作者。
一本书有一个ISBN代码。
一本书可以放在一个或多个流派中。
现在,我们仍然需要对顾客进行建模。 从逻辑上讲,这将是一个 Patron
类。
import java.util.ArrayList;
import java.util.List;
public class Patron {
private String name;
private String address;
private String phoneNumber;
private List<Book> checkedOut;
public Patron(String name, String address, String phoneNumber) {
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
this.checkedOut = new ArrayList<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public List<Book> getCheckedOut() {
return checkedOut;
}
public void addCheckedOut(Book checkedOut) {
this.checkedOut.add(checkedOut);
}
public void removeCheckedOut(Book returned) {
this.checkedOut.remove(returned);
}
}
我想你已经明白了应用模型的概念。
首先,创建完整的应用模型。
其次,从应用模型中,创建你的SQL表。 创建一个 SQL
类来保存所有的SQL代码。 我没有看到你的代码足以创建一个 SQL
类为你服务。
第三,创建Swing GUI。 这一步你可以使用Swing默认模型。
下面是我的一个SQL类,让你了解应该如何编写SQL类的代码。 我使用的是MySQL。 你应该始终使用准备好的语句来防止 SQL注入攻击.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import com.amazon.ask.model.User;
import com.ggl.bible.reader.model.Book;
import com.ggl.bible.reader.model.Verse;
import com.ggl.bible.reader.model.VerseKey;
public class SQL {
private Connection connection;
public boolean connect() {
try {
String[] params = createConnectionStrings();
connection = DriverManager.getConnection(params[0],
params[1], params[2]);
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
private String[] createConnectionStrings() {
String[] connection = new String[3];
String host = "bible-database.caaitaoyrsgp.us-east-1."
+ "rds.amazonaws.com";
String port = "3306";
String user = "ggleblanc";
String useSSL = "?useSSL=false";
String schema = "/bible";
String password = "******************";
String driver = "jdbc:mysql://" + host + ":" + port;
driver += schema + useSSL;
connection[0] = driver;
connection[1] = user;
connection[2] = password;
return connection;
}
public void close() {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public Optional<Timestamp> selectLastCreated() {
StringBuilder builder = new StringBuilder();
builder.append("SELECT `timestamp` ");
builder.append(" FROM `bible`.`lastCreated` ");
builder.append(" ORDER BY `timestamp` DESC ");
builder.append(" LIMIT 0, 1; ");
String sql = builder.toString();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
rs.next();
Optional<Timestamp> timestamp = Optional.of(
rs.getTimestamp(1));
rs.close();
return timestamp;
} catch (SQLException e) {
e.printStackTrace();
return Optional.empty();
}
}
public List<Book> selectBooks() {
List<Book> books = new ArrayList<>();
StringBuilder builder = new StringBuilder();
builder.append("SELECT `bookId`, `bookShortName`, ");
builder.append(" `bookName` ");
builder.append(" FROM `bible`.`book`; ");
String sql = builder.toString();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
int bookID = rs.getInt("bookID");
String bookShortName = rs.getString(
"bookShortName");
String bookName = rs.getString("bookName");
Book book = new Book(bookID, bookShortName,
bookName);
books.add(book);
}
rs.close();
return books;
} catch (SQLException e) {
e.printStackTrace();
return new ArrayList<Book>();
}
}
public int selectLastChapter(int bookID) {
StringBuilder builder = new StringBuilder();
builder.append("SELECT MAX(`chapter`) ");
builder.append(" FROM `bible`.`verse` ");
builder.append(" WHERE `bookID` = ? ");
String sql = builder.toString();
try {
PreparedStatement statement =
connection.prepareStatement(sql);
statement.setInt(1, bookID);
ResultSet rs = statement.executeQuery();
rs.next();
int result = rs.getInt(1);
rs.close();
return result;
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}
public int selectLastVerse(int bookID, int chapter) {
StringBuilder builder = new StringBuilder();
builder.append("SELECT MAX(`verse`) ");
builder.append(" FROM `bible`.`verse` ");
builder.append(" WHERE `bookID` = ? ");
builder.append(" AND `chapter` = ? ");
String sql = builder.toString();
try {
PreparedStatement statement =
connection.prepareStatement(sql);
statement.setInt(1, bookID);
statement.setInt(2, chapter);
ResultSet rs = statement.executeQuery();
rs.next();
int result = rs.getInt(1);
rs.close();
return result;
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}
public List<Verse> selectPassage(VerseKey startVerseKey,
VerseKey endVerseKey) {
List<Verse> verses = new ArrayList<>();
String[] sql = new String[2];
StringBuilder builder = new StringBuilder();
builder.append("SELECT `verseID` ");
builder.append(" FROM `bible`.`verse` ");
builder.append(" WHERE `bookID` = ? ");
builder.append(" AND `chapter` = ? ");
builder.append(" AND `verse` = ?; ");
sql[0] = builder.toString();
builder = new StringBuilder();
builder.append("SELECT `bookID`, `chapter`, `verse`, "
+ "`text` ");
builder.append(" FROM `bible`.`verse` ");
builder.append(" WHERE `verseID` BETWEEN ? AND ? ");
sql[1] = builder.toString();
try {
PreparedStatement statement =
connection.prepareStatement(sql[0]);
statement.setInt(1, startVerseKey.getBookID());
statement.setInt(2, startVerseKey.getChapter());
statement.setInt(3, startVerseKey.getVerse());
ResultSet rs = statement.executeQuery();
if (!rs.next()) {
rs.close();
return verses;
}
int startIndex = rs.getInt("verseID");
rs.close();
statement.setInt(1, endVerseKey.getBookID());
statement.setInt(2, endVerseKey.getChapter());
statement.setInt(3, endVerseKey.getVerse());
rs = statement.executeQuery();
if (!rs.next()) {
rs.close();
return verses;
}
int endIndex = rs.getInt("verseID");
rs.close();
statement = connection.prepareStatement(sql[1]);
statement.setInt(1, startIndex);
statement.setInt(2, endIndex);
rs = statement.executeQuery();
while (rs.next()) {
int bookID = rs.getInt("bookID");
int chapter = rs.getInt("chapter");
int verseNum = rs.getInt("verse");
String text = rs.getString("text");
Verse verse = new Verse(bookID, chapter,
verseNum, text);
verses.add(verse);
}
rs.close();
return verses;
} catch (SQLException e) {
e.printStackTrace();
return new ArrayList<Verse>();
}
}
public Optional<Verse> selectNextVerse(VerseKey verseKey) {
String[] sql = new String[2];
StringBuilder builder = new StringBuilder();
builder.append("SELECT `verseID` ");
builder.append(" FROM `bible`.`verse` ");
builder.append(" WHERE `bookID` = ? ");
builder.append(" AND `chapter` = ? ");
builder.append(" AND `verse` = ?; ");
sql[0] = builder.toString();
builder = new StringBuilder();
builder.append("SELECT `bookID`, `chapter`, "
+ "`verse`, `text` ");
builder.append(" FROM `bible`.`verse` ");
builder.append(" WHERE `verseID` = ? ");
sql[1] = builder.toString();
try {
PreparedStatement statement =
connection.prepareStatement(sql[0]);
statement.setInt(1, verseKey.getBookID());
statement.setInt(2, verseKey.getChapter());
statement.setInt(3, verseKey.getVerse());
ResultSet rs = statement.executeQuery();
if (!rs.next()) {
rs.close();
return Optional.empty();
}
int verseID = rs.getInt("verseID");
rs.close();
statement = connection.prepareStatement(sql[1]);
statement.setInt(1, verseID + 1);
rs = statement.executeQuery();
if (!rs.next()) {
rs.close();
return Optional.empty();
}
int bookID = rs.getInt("bookID");
int chapter = rs.getInt("chapter");
int verseNum = rs.getInt("verse");
String text = rs.getString("text");
Verse verse = new Verse(bookID, chapter,
verseNum, text);
rs.close();
return Optional.of(verse);
} catch (SQLException e) {
e.printStackTrace();
return Optional.empty();
}
}
public int selectVisitCount(User user) {
StringBuilder builder = new StringBuilder();
builder.append("SELECT `numberOfVisits` ");
builder.append(" FROM `bible`.`archive` ");
builder.append(" WHERE `userID` = ?; ");
String sql = builder.toString();
String userID = user.getUserId();
try {
PreparedStatement statement =
connection.prepareStatement(sql);
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();
if (!rs.next()) {
rs.close();
return -1;
}
int result = rs.getInt(1);
rs.close();
return result;
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}
public int[] selectPassageChapter(User user) {
StringBuilder builder = new StringBuilder();
builder.append("SELECT `passageBookID`, "
+ "`passageChapter`, ");
builder.append(" `passageVerse` ");
builder.append(" FROM `bible`.`archive` ");
builder.append(" WHERE `userID` = ?; ");
String sql = builder.toString();
String userID = user.getUserId();
try {
int[] output = {-1, -1, -1};
PreparedStatement statement =
connection.prepareStatement(sql);
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();
if (!rs.next()) {
rs.close();
return output;
}
output[0] = rs.getInt("passageBookID");
output[1] = rs.getInt("passageChapter");
output[2] = rs.getInt("passageVerse");
rs.close();
return output;
} catch (SQLException e) {
e.printStackTrace();
int[] output = {-1, -1, -1};
return output;
}
}
public int[] selectReadingChapter(User user) {
StringBuilder builder = new StringBuilder();
builder.append("SELECT `readingBookID`, "
+ "`readingChapter`, ");
builder.append(" `readingStartVerse`, "
+ "`readingEndVerse` ");
builder.append(" FROM `bible`.`archive` ");
builder.append(" WHERE `userID` = ?; ");
String sql = builder.toString();
String userID = user.getUserId();
try {
int[] output = {-1, -1, -1, -1};
PreparedStatement statement =
connection.prepareStatement(sql);
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();
if (!rs.next()) {
rs.close();
return output;
}
output[0] = rs.getInt("readingBookID");
output[1] = rs.getInt("readingChapter");
output[2] = rs.getInt("readingStartVerse");
output[3] = rs.getInt("readingEndVerse");
rs.close();
return output;
} catch (SQLException e) {
e.printStackTrace();
int[] output = {-1, -1, -1, -1};
return output;
}
}
public void insertArchiveRow(User user) {
StringBuilder builder = new StringBuilder();
builder.append("INSERT INTO `bible`.`archive` ");
builder.append(" (`archiveID`, `numberOfVisits`, ");
builder.append(" `readingBookID`, `readingChapter`, ");
builder.append(" `readingStartVerse`, "
+ "`readingEndVerse`, ");
builder.append(" `passageBookID`, ");
builder.append(" `passageChapter`, `passageVerse`, ");
builder.append(" `lastVisitTimeStamp`, `userID`) ");
builder.append("VALUES (DEFAULT, ?, ?, ?, "
+ "?, ?, ?, ?, ?, ");
builder.append(" CURRENT_TIMESTAMP, ?); ");
String sql = builder.toString();
String userID = user.getUserId();
try {
connection.setAutoCommit(false);
PreparedStatement statement =
connection.prepareStatement(sql);
statement.setInt(1, 1);
statement.setInt(2, 0);
statement.setInt(3, 0);
statement.setInt(4, 0);
statement.setInt(5, 0);
statement.setInt(6, 0);
statement.setInt(7, 0);
statement.setInt(8, 0);
statement.setString(9, userID);
statement.executeUpdate();
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateVisitCount(User user) {
StringBuilder builder = new StringBuilder();
builder.append("UPDATE `bible`.`archive` ");
builder.append("SET `numberOfVisits` = "
+ "`numberOfVisits` + 1, ");
builder.append(" `lastVisitTimestamp` = "
+ "CURRENT_TIMESTAMP ");
builder.append("WHERE `userID` = ? ");
String sql = builder.toString();
String userID = user.getUserId();
try {
connection.setAutoCommit(false);
PreparedStatement statement =
connection.prepareStatement(sql);
statement.setString(1, userID);
statement.executeUpdate();
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updatePassageChapter(User user,
VerseKey verseKey) {
StringBuilder builder = new StringBuilder();
builder.append("UPDATE `bible`.`archive` ");
builder.append("SET `passageBookID` = ?, ");
builder.append(" `passageChapter` = ?, ");
builder.append(" `passageVerse` = ? ");
builder.append("WHERE `userID` = ? ");
String sql = builder.toString();
String userID = user.getUserId();
try {
connection.setAutoCommit(false);
PreparedStatement statement =
connection.prepareStatement(sql);
statement.setInt(1, verseKey.getBookID());
statement.setInt(2, verseKey.getChapter());
statement.setInt(3, verseKey.getVerse());
statement.setString(4, userID);
statement.executeUpdate();
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateReadingChapter(User user,
VerseKey verseKey, int endVerse) {
StringBuilder builder = new StringBuilder();
builder.append("UPDATE `bible`.`archive` ");
builder.append("SET `readingBookID` = ?, ");
builder.append(" `readingChapter` = ?, ");
builder.append(" `readingStartVerse` = ?, ");
builder.append(" `readingEndVerse` = ? ");
builder.append("WHERE `userID` = ? ");
String sql = builder.toString();
String userID = user.getUserId();
try {
connection.setAutoCommit(false);
PreparedStatement statement =
connection.prepareStatement(sql);
statement.setInt(1, verseKey.getBookID());
statement.setInt(2, verseKey.getChapter());
statement.setInt(3, verseKey.getVerse());
statement.setInt(4, endVerse);
statement.setString(5, userID);
statement.executeUpdate();
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
}