📄 dbbean.java
字号:
package mypack;
import java.sql.*;
import java.util.*;
import com.microsoft.jdbc.sqlserver.SQLServerDriver;
public class DBBean {
public static void main(String[] args) {
try{
String driver="com.microsoft.jdbc.sqlserver.SQLServerDriver;";
String user="sa";
String pwd="sa";
String url="jdbc:microsoft:sqlserver://localhost:1433;databaseName=pubs";
//加载jdbc的驱动
Class.forName(driver);
//连接数据库
Connection con=DriverManager.getConnection(url, user,pwd);
//编写sql命令
String sql="select * from books";
Statement stm=con.createStatement();
ResultSet rs=stm.executeQuery(sql);
Vector v=new Vector();
while(rs.next()){
String id=rs.getString("id");
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对象
BookBean book=new BookBean(id,name,title,price,yr,description,saleAmount);
v.add(book);
}
Iterator i= v.iterator();
while(i.hasNext()){
BookBean b=(BookBean)i.next();
System.out.print(b.getId());
System.out.print(b.getName());
System.out.print(b.getTitle());
System.out.print(b.getPrice());
System.out.print(b.getYr());
System.out.print(b.getDescription());
System.out.println(b.getSaleAmount());
}
rs.close();
stm.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}
BookBean book=new BookBean("207","宋霞","ytuoiery",12.60f,2008,"yuweyrew",2140);
add(book);
}
public static void add(BookBean book){
try{
String driver="com.microsoft.jdbc.sqlserver.SQLServerDriver;";
String user="sa";
String pwd="sa";
String url="jdbc:microsoft:sqlserver://localhost:1433;databaseName=pubs";
Class.forName(driver);
Connection con=DriverManager.getConnection(url, user, pwd);
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());
pstm.executeUpdate();
}
catch(Exception e){
e.printStackTrace();
}
}
public void Update(BookBean book){
try{
String driver="com.microsoft.jdbc.sqlserver.SQLServerDriver;";
String user="sa";
String pwd="sa";
String url="jdbc:microsoft:sqlserver://localhost:1433;databaseName=pubs";
Class.forName(driver);
Connection con=DriverManager.getConnection(url, user, pwd);
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());
pstm.executeUpdate();
}
catch(Exception e){
e.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -