Skip to main content
 首页 » 编程设计

c#之插入行的返回值

2024年02月13日13cloudgamer

我需要返回插入记录的值以传递给代码以打开表单。我如何获得该值?下面的代码添加一条记录并刷新一个数据 GridView 。

System.Data.SqlClient.SqlConnection sqlConnection1 = 
                 new System.Data.SqlClient.SqlConnection("Data Source=***.**.***.**,****;Initial Catalog=newCityCollection_Aracor;Persist Security Info=True;User ID=4456r;Password=654935749653"); 
 
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(); 
cmd.CommandType = System.Data.CommandType.Text; 
cmd.CommandText = "INSERT PropertyInformation (ClientKey) VALUES (1)"; 
cmd.Connection = sqlConnection1; 
 
sqlConnection1.Open(); 
cmd.ExecuteNonQuery(); 
sqlConnection1.Close(); 
 
this.propertyInformationDataGridView.Invalidate(); 
this.propertyInformationDataGridView.EndEdit(); 
this.propertyInformationDataGridView.Refresh(); 
this.newCityCollectionDataSet.AcceptChanges(); 
this.propertyInformationTableAdapter.Fill(newCityCollectionDataSet.PropertyInformation);  

请您参考如下方法:

将您的 SQL 更改为:

INSERT PropertyInformation (ClientKey) VALUES (1); 
SELECT * FROM PropertyInformation WHERE RecordID = scope_identity() 

scope_identity() 应该为您提供当前 session 的最后插入标识列(记录 ID),这将是您刚刚插入到 PropertyInformation 中的行的 ID。