对数据库操作时,需要保留刚插入的新行的标识列以备后用,下面是用SQL语句实现方法:
private SqlConnection connection;
//连接字符串
this.connection = new SqlConnection();
this.connection.ConnectionString =
@"Data Source=.;Initial Catalog=DBDemo;Persist Security Info=True;User ID=sa;Password=123";
this.connection.Open();
//SQL语句
SqlCommand command = new SqlCommand();
command.Connection = this.connection;
command.CommandType = CommandType.Text;
string sql = string.Format(
"insert into ……");
command.CommandText = sql;
//执行SQL语句
command.ExecuteNonQuery();
//获取标识列的SQL语句
string sequel = "SELECT @@IDENTITY"; //主要是这句
SqlCommand comm = new SqlCommand();
comm.Connection = this.connection;
comm.CommandType = CommandType.Text;
comm.CommandText = sequel;
//执行SQL语句,获取新插入行的标识列
object id = comm.ExecuteScalar();
介绍@@IDENTITY的文章可以从下面找到
http://baike.baidu.com/view/1592444.htm