如何在C#
中将数据库返回的PolicyID
的值存储在一个整型变量中?
我正在使用 SQL Server 2005。
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =
@"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
dataCommand.CommandText = ("select PolicyID from Policies where PolicyID=(select max(PolicyID) from Policies)");
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
请提出建议。
谢谢。
最佳答案
使用 SqlCommand.ExecuteScalar方法,像这样:
command.CommandText = @"select max(PolicyID) from Policies";
int maxPolicyId = (int)command.ExecuteScalar();
此外,如果您这样做是为了插入具有唯一 ID 的新政策行,则不得这样做,因为完全有可能在选择和插入之间插入不同的政策行。
而是使用 IDENTITY
列或 UNIQUEIDENTIFIER
列。
编辑:要在您的代码中使用它,请执行以下操作:
int maxId;
using (SqlConnection dataConnection = new SqlConnection(@"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True"))
using (SqlCommand dataCommand =
new SqlCommand("select max(PolicyID) from Policies", dataConnection)) {
dataConnection.Open();
maxId = Convert.ToInt32(dataCommand.ExecuteScalar());
}
关于c# - 使用 select 语句后将值存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1555320/