對數據庫操作時,需要保留剛插入的新行的標識列以備後用,下面是用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