📄 bookdb.java
字号:
package mypack;
import java.sql.*;
import java.util.*;
import java.lang.*;
public class BookDB {
String driver="com.microsoft.jdbc.sqlserver.SQLServerDriver";
String user="sa";
String pwd="sa";
String url="jdbc:microsoft:sqlserver://localhost:1433;databaseName=pubs";
private Connection con;
private Connection getCon() {
try{
Class.forName(driver);
Connection con=DriverManager.getConnection(url, user, pwd);
return con;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
//获取一本图书信息
//参数:图书编号;返回类型:bookbean对象
public BookBean getBook(String id ){
try{
String sql="select *from books where id="+id;
Connection con=getCon();
Statement stm=con.createStatement();
BookBean book=null;
ResultSet rs=stm.executeQuery(sql);
while(rs.next()){
String bookid=rs.getString(1);
String name=rs.getString(2);
String title=rs.getString(3);
float price=rs.getFloat(4);
int yr=rs.getInt(5);
String description=rs.getString(6);
int saleAmount=rs.getInt(7);
book=new BookBean(bookid,name,title,price,yr,description,saleAmount);
}
rs.close();
stm.close();
con.close();
return book;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
//获取所有的图书信息
// 参数:无;返回类型:vector
public Vector getBooks(){
try{
String sql="select * from books";
Connection con=getCon();
Statement stm=con.createStatement();
ResultSet rs=stm.executeQuery(sql);
Vector v=new Vector();
while(rs.next()){
String bookid=rs.getString(1);
String name=rs.getString(2);
String title=rs.getString(3);
float price=rs.getFloat(4);
int yr=rs.getInt(5);
String description=rs.getString(6);
int saleAmount=rs.getInt(7);
BookBean book=new BookBean(bookid,name,title,price,yr,description,saleAmount);
v.add(book);
}
return v;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
//添加一本书
//参数:一本图书信息bookbean对象;返回类型boolean,代表是否添加成功
public boolean addBook(BookBean book){
try{
Connection con=getCon();
String sql="insert books Values(?,?,?,?,?,?,?)";//变量
PreparedStatement pstm=con.prepareStatement(sql);//传参
pstm.setString(1,book.getId());//通过book对象给id 赋值
pstm.setString(2,book.getName());
pstm.setString(3,book.getTitle());
pstm.setFloat(4,book.getPrice());
pstm.setInt(5,book.getYr());
pstm.setString(6,book.getDescription());
pstm.setInt(7,book.getSaleAmount());
int flg= pstm.executeUpdate();
pstm.close();
con.close();
if(flg!=0){return true;}
}catch(Exception e){
e.printStackTrace();
}
return false;
}
public boolean delBook(String id){
try{
String sql="delete from books where id="+id;
Connection con=getCon();
Statement stm=con.createStatement();
int flg=stm.executeUpdate(sql);
if(flg!=0){return true;}
}catch(Exception e){
e.printStackTrace();
}
return false;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -