时间:2021-07-01 10:21:17 帮助过:12人阅读
为每一张表建立一个实体类,实体类中的属性对应着表的字段名。
1 package qddx.JDBC; 2 import java.sql.*; 3 public class bbsVo { 4 5 private int id; 6 private int pid; 7 private int rootid; 8 private String title; 9 private String cont; 10 private Timestamp pdate; 11 private int isleaf; 12 13 public int getId(){ 14 return id; 15 } 16 public void setId(int id){ 17 this.id = id; 18 } 19 20 public int getPid(){ 21 return pid; 22 } 23 public void setPid(int pid){ 24 this.pid = pid; 25 } 26 27 public int getRootid(){ 28 return rootid; 29 } 30 public void setRootid(int rootid){ 31 this.rootid = rootid; 32 } 33 34 public String getTitle(){ 35 return cont; 36 } 37 public void setCont(String title){ 38 this.title = title; 39 } 40 41 public String getCont(){ 42 return title; 43 } 44 public void setTitle(String cont){ 45 this.cont = cont; 46 } 47 public Timestamp getPdate(){ 48 return pdate; 49 } 50 public void setPdate(Timestamp pdate){ 51 this.pdate = pdate; 52 } 53 54 public int getIsleaf(){ 55 return isleaf; 56 } 57 public void setIsleaf(int isleaf){ 58 this.isleaf = isleaf; 59 } 60 61 }
插入数据
package qddx.JDBC; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.Timestamp; import java.sql.*; public class Addbbs { public void add(bbsVo vo){ Connection conn = null; PreparedStatement pst = null; ResultSet rs = null; try{ conn = JDBC_Connection.getConnection(); String sql = "INSERT INTO ARTICLE(id,pid,rootid,title,cont,pdate,isleaf) values(?,?,?,?,?,?,?)"; pst=conn.prepareStatement(sql); //把相应的参数 添加到pst对象中 pst.setInt( 1, vo.getId()); pst.setInt(2, vo.getPid()); pst.setInt(3, vo.getRootid()); pst.setString(4, vo.getTitle()); pst.setString(5, vo.getCont()); pst.setTimestamp(6, vo.getPdate()); pst.setInt(7, vo.getIsleaf()); //提交pst对象 pst.executeUpdate(); }catch(SQLException e){ e.printStackTrace(); }finally{ JDBC_Connection.free(rs, conn, pst);//关闭数据库连接 } } public static void main(String[] args) { // TODO Auto-generated method stub Addbbs addbbs = new Addbbs(); bbsVo vo = new bbsVo(); int id=13; int pid = 10; int rootid = 1; String title = "蚂蚁"; String cont = "蚂蚁"; java.util.Date date = new java.util.Date(); Timestamp pdate = new Timestamp(date.getTime()); int isleaf = 1; //设置要添加的变量值,放入bbsvo中 vo.setId(id); vo.setPid(pid); vo.setRootid(rootid); vo.setTitle(cont); vo.setCont(title); vo.setIsleaf(isleaf); vo.setPdate(pdate); addbbs.add(vo); } }
JDBC向数据库中插入数据
标签: