【问题标题】:How to store Max value of a column as a integer in a database table?如何将列的最大值存储为数据库表中的整数?
【发布时间】:2018-05-08 07:27:42
【问题描述】:

我在 SQL Server Management Studio 中创建了一个表(表名 - tblSample)。其中包含字段 id 和名称。我想要做的是选择 id 的最大值,我可以使用以下查询:

SELECT MAX(id) FROM tblSample;

现在我想将最大 id 存储为 C# 中的整数值。我该怎么做。

【问题讨论】:

  • 问题不完整。你想把它存放在哪里?到目前为止,您尝试过什么?
  • 你想在其他表或变量中存储最大 id 的位置

标签: asp.net sql-server c#-4.0


【解决方案1】:

根据您的问题:

private void GetData()
    {
        //1
        string connetionString = "Data Source=ServerName;Initial 
            Catalog=DatabaseName;User ID=UserName;Password=Password";

        //2
        string sql = "SELECT MAX(id) FROM tblSample";

        SqlConnection sqlCnn;
        SqlCommand sqlCmd;

        //3
        sqlCnn = new SqlConnection(connetionString);
        int storeMaxId = 0;
        try
        {
            //4
            sqlCnn.Open();
            //5
            sqlCmd = new SqlCommand(sql, sqlCnn);
            //6
            storeMaxId = Convert.ToInt32(sqlCmd.ExecuteScalar());
            //7
            sqlCmd.Dispose();
            sqlCnn.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Can not open connection ! ");
        }
    }

1:这是连接字符串。该行是不言自明的,您必须输入您的服务名称、数据库名称等。

2:这是您要执行的查询。

3:您从 1 中获取连接字符串并使用 SqlConnection 类来创建到您的数据库的连接。

4:打开连接

5:使用 SqlCommand 类创建命令,使用 1 和 2 中的值作为参数。

6:您使用 ExecuteScalar 方法执行命令并获取单个值。将其转换为 int 并存储在变量中。

7:处理所有打开的连接(很重要)

【讨论】:

    猜你喜欢
    • 2022-11-24
    • 1970-01-01
    • 2011-03-05
    • 2013-08-04
    • 2019-06-13
    • 2019-01-22
    • 2018-09-23
    相关资源
    最近更新 更多