ExecuteScalar 方法不只可以用在数据库的 SELECT 作业,亦可用于 INSERT 作业。假设我们想要在 INSERT 一笔 record 至数据库后,马上取得刚才新增那一笔 record 的 Identity (自动增号) 的值,可用下列 SQL statement 达成:
string strSql = "INSERT INTO 数据表 (name, age) VALUES (''David'', 20); Select @@Identity";
或者 string strSql = "INSERT INTO 数据表 (name, age) VALUES (''David'', 20); Select scope_identity()";
此时,我们即可用 ExecuteScalar 方法,取代 ExecuteNonQuery 方法,去执行上述这一段 SQL statement,以便返回一笔计算过的「单一值」,亦即最新的 Identity 流水号码,关键 ADO.NET 代码如下: SqlConnection conn = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand(strSqlStr, conn);
try
{
conn.Open();
if (conn.State == ConnectionState.Open)
{
// 返回最新的 Identity 流水号码
intNewestSerialNum = Convert.ToInt32(cmd.ExecuteScalar());
}
}
catch (SqlException ex)
{
}
这个是.Net文档里已经有说明的,不过木鸟把它整理了一下,大家用起来方便一些
先说sql server数据库,因为比较简单,和asp里一样
myCommand.CommandText="intert into table (a) values (''a'') select @@identity";
int newID=Int32.Parse(myCommand.ExecuteScalar());
这里要用Int32.Parse,没办法,按说object可以直接显示转换为int,但我试了后老报错,只好麻烦点了
Access数据库麻烦很多,只能用DataAdapter的Update(DataSet,string)来进行插入数据才能得到新记录ID,下边基本和文档里的一样,我改了一点,这样比较不那么麻烦
class Sample
{
int newID;
OleDbConnection Conn = new OleDbConnection("...");
....
....
protected void InertRow()
{
OleDbDataAdapter catDA = new OleDbDataAdapter("select a from table",Conn);
DataSet ds=new DataSet();
Conn.Open();
catDA.Fill(ds,"Cat");
DataRow newrow=ds.Tables["Cat"].NewRow();
newrow["a"]="a";
ds.Tables["Cat"].Rows.Add(newrow);
// Include an event to fill in the Autonumber value.
catDA.RowUpdated += new OleDbRowUpdatedEventHandler(OnRowUpdated);
catDA.Update(ds, "Cat");
Conn.Close();
Response.Write("新ID:"+newID);
}
protected void OnRowUpdated(object sender, OleDbRowUpdatedEventArgs args)
{
// Include a variable and a command to retrieve the identity value from the Access database.
OleDbCommand idCMD = new OleDbCommand("SELECT @@IDENTITY", Conn);
if (args.StatementType == StatementType.Insert)
{
// Retrieve the identity value and store it in the CategoryID column.
newID = (int)idCMD.ExecuteScalar();
}
}
}