mysql中的auto_increment如何重新赋值 ---PreparedStatement的setNull()

来源:互联网 发布:npm i node sass d 编辑:程序博客网 时间:2024/06/11 15:26
在mysql设置过auto_increment最好不要自己给它赋值;要是想赋值可以通过PreparedStatement.setNull(inti,int Type)设置
我的MVC ---DAO例子中,通过参数传递向mysql数据库中赋值,但是note(id,title,author,content)中的id是自动增值的(auto_increment),如何对其赋值呢???
代码:

public void insert(Note note)throws Exception
 {
  String sql = "INSERT INTOnote(id,title,author,content) VALUES(?,?,?,?)" ;
  PreparedStatement pstmt = null;
  DataBaseConnection dbc = null;
  dbc = new DataBaseConnection();
  try
  {
   pstmt =dbc.getConnection().prepareStatement(sql);

   //关键代码,费了很多时间才找到的解决办法
   pstmt.setNull(1,1);
   pstmt.setString(2,note.getTitle());
   pstmt.setString(3,note.getAuthor());
   pstmt.setString(4,note.getContent());
   
   pstmt.executeUpdate();
   pstmt.close();
  }
  catch (Exception e)
  {
   //System.out.println(e) ;
   throw newException("操作中出现错误!!!") ;
  }
  finally
  {
   dbc.close();
  }
 }


ps:1.当已经给auto_increment赋某值时,继续赋相同值给它,会出错。

2.在java中如果要insert一行数据给数据表,且该行有auto_increment,如果auto_increment没有初值,会报错。

如果auto_increment已有值,则sql语句中auto_increment对应的值应为null,如:

con.modify(sql,null,user, password, contact, email);

0 0
原创粉丝点击