您的位置:首页 > 数据库 > MySQL

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

2013-12-21 15:22 351 查看
在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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息