📄 librarybooks.java
字号:
package library;
import java.sql.*;
import java.util.ArrayList;
public class LibraryBooks {
// This ArrayList store all books names in library
private ArrayList <LibraryBooks> books = new ArrayList <LibraryBooks>();
private String dbUrl = "jdbc:postgresql://localhost/library";
private String dbUser = "postgres";
private String dbPwd = "123";
Connection con = null;
PreparedStatement prepStmt = null;
ResultSet rs = null;
private String name;
private String isbn;
public LibraryBooks(){
}
public LibraryBooks(String isbn,String name){
this.name = name;
this.isbn = isbn;
}
public Connection getConnection() throws Exception {
return DriverManager.getConnection(dbUrl, dbUser, dbPwd);
}
public void closeConnection(Connection con) {
try {
if (con != null)
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void closeResultSet(ResultSet rs) {
try {
if (rs != null)
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void closePrepStmt(PreparedStatement prepStmt) {
try {
if (prepStmt != null)
prepStmt.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// Get all books
public ArrayList <LibraryBooks> getAllBooks() throws Exception {
try {
Class.forName("org.postgresql.Driver").newInstance();
con = getConnection();
String selectStatement = "select * from Title5";
prepStmt = con.prepareStatement(selectStatement);
rs = prepStmt.executeQuery();
while (rs.next()) {
LibraryBooks book = new LibraryBooks(rs.getString(2),rs.getString(4));
books.add(book);
}
return books;
} finally {
closeResultSet(rs);
closePrepStmt(prepStmt);
closeConnection(con);
}
}
public String getTitle(String isbn) throws Exception {
try {
Class.forName("org.postgresql.Driver").newInstance();
con = getConnection();
String selectStatement = "select * from Title5 where isbn=?";
prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1,isbn);
rs = prepStmt.executeQuery();
if (rs.next()) {
String name = rs.getString(4);
return name;
} else{
return "not in";
}
} finally {
closeResultSet(rs);
closePrepStmt(prepStmt);
closeConnection(con);
}
}
public String getName() {
return name;
}
public String getISBN(){
return isbn;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -