c# - 使用 select 语句后将值存储在变量中

标签 c# asp.net sql-server visual-studio

如何在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/

相关文章:

html - Bootstrap 在一行和一列中使用图像渲染文本

css - 使用 Html.BeginForm 和语义 UI

sql - 从 SQL Server 中的 xml,获取下一个兄弟值

C# - 将属性值从一个实例复制到另一个不同的类

c# - 如何将复杂类型转换为 actionresult

c# - 验证小数是否具有三个位置

sql - t-sql使用内连接更新多行

C#网络应用程序用户无故注销

c# - SQL 查询错误 - "Column cannot be null"

c# - 从选择查询返回 bool 值