数据库data中表person中有id(主键,自动生成),age,name字段,现插入数据,返回插入数据的Id值,而不是返回影响的行数,以下代码返回的是影响的行数,我用select @@identity还是一样的效果,如何修改可以返回插入数据当前行的id值
string str = "Data Source=.;Initial Catalog=data;Integrated Security=True";
SqlConnection conn = new SqlConnection(str);
string sql = "insert into person (Age,Name) output inserted.Id values(20,'name');select @@identity";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
int i=(int)cmd.ExecuteScalar();
conn.close();
MessageBox.Show(i.ToString());
//插入数据后获取最新的自动编号方法
public static int ExecuteInsertGetId(string sql)
{
int i = 0;
using (SqlConnection DCon = new SqlConnection(AllVar.SysConChar))
{
DCon.Open();
SqlCommand cmd = new SqlCommand(sql + ";select @@IDENTITY");
cmd.Connection = DCon;
try
{
i = Convert.ToInt32(cmd.ExecuteScalar());
}
catch
{
i = 0;
}
}
return i;
}
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did17