关于ms-sql中主键自增的插入

发布时间:2024-05-21 17:48 发布:上海旅游网

问题描述:

原来我的程序是采用oracle数据库的 现在我想吧数据迁移到ms-sql中

代码:
下面为在oracle中建的表
CREATE SEQUENCE note_sequ ;

CREATE TABLE note
(
id int not null primary key , -- sequence
title varchar(20) not null ,
author varchar(20) not null ,
content varchar(50) not null
) ;

commit ;

下面为部分代码 采用了DAO模式 oracle中能调试通过.

import java.sql.* ;
import java.util.* ;
import user.note.vo.* ;
import user.note.dao.* ;
import user.note.dbc.* ;

public class NoteDAOImpl implements NoteDAO
{

public void insert(Note note) throws Exception
{

String sql = "INSERT INTO note(id,title,author,content) VALUES(note_sequ.nextVal,?,?,?)" ;

PreparedStatement pstmt = null ;
DataBaseConnection dbc = null ;
dbc = new DataBaseConnection() ;
try
{
pstmt = dbc.getConnection().prepareStatement(sql) ;
pstmt.setString(1,note.getTitle()) ;
pstmt.setString(2,note.getAuthor()) ;
pstmt.setString(3,note.getContent()) ;
pstmt.executeUpdate() ;
pstmt.close() ;
}
catch (Exception e)
{

throw new Exception("操作中出现错误!!!") ;
}
finally
{
dbc.close() ;
}
}

}

现在我已经在ms-sql键好了表 id主键 自增1 其他字段与oracle中相同

现在我想插入数据时
String sql = "INSERT INTO note(id,title,author,content) VALUES(note_sequ.nextVal,?,?,?)" 这句话中的note_sequ.nextVal字段用什么代替??? 谢谢大侠们帮帮忙 ,谢谢。
终于调试出来了 现在给分

问题解答:

sqlserver里,自动增加不用在sql里写,数据库会自动增加的,不用写
也就是说,insert语句里不用写id

试一下吧,sqlserver的自增量和ORACLE不同,不用另外写,能自动加的

要么你就插个null好了

用null就可以 或者直接不指定它的列名

不用插 mysql自己会自增的

热点新闻