定义对象:
package jdbc;
public class ShangPin {
private int id;
private String name;
private int buyInPrice;
private int unitPrice;
private int stock;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getBuyInPrice() {
return buyInPrice;
}
public void setBuyInPrice(int buyInPrice) {
this.buyInPrice = buyInPrice;
}
public int getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(int unitPrice) {
this.unitPrice = unitPrice;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
}
包装方法:
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public class ShangPinManager {
private final static String DRIVER = "com.mysql.jdbc.Driver";
private final static String URL = "jdbc:mysql://127.0.0.1:3306/e-market";
private final static String USER = "root";
private final static String PWD = "1992";
public int AddShangPin(ShangPin sp) throws ClassNotFoundException, SQLException{
int n = -1;
Class.forName(DRIVER);
Connection conn = DriverManager.getConnection(URL, USER, PWD);
java.sql.Statement st = conn.createStatement();
String sql = "insert into commodityinfo(CID,CName,InputPrice,OutputPrice,Amount)"
+"values(null,'"+sp.getName()+"','"+sp.getBuyInPrice()+"','"
+sp.getUnitPrice()+"','"+sp.getStock()+"')";
n = st.executeUpdate(sql);
if(n>=1){
JOptionPane.showMessageDialog(null, "添加商品成功");
}else{
JOptionPane.showMessageDialog(null, "添加商品失败");
}
return n;