mysql java使用PreparedStatement插入數據並返回id的代碼

java使用PreparedStatement插入數據到mysql並返回id 的源代碼

public int add(Video vd) throws Exception {
  String sql="insert into msg_video_data(name,`rename`,title,content,date,src) values(?,?,?,?,?,?)";
  int id=0;
  try{
   conn=getConns();
   ps=conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
   ps.setString(1, vd.getName());
   ps.setString(2, vd.getRename());
   ps.setString(3, vd.getTitle());
   ps.setString(4, vd.getContent());
   ps.setString(5, vd.getDate());
   ps.setString(6,vd.getSrc());
   ps.executeUpdate();
   
   rs=ps.getGeneratedKeys();
   rs.next();
   id=rs.getInt(1);
  }catch(Exception e){
   throw e;
  }finally{
   close();
  }
  return id;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章