4

我对 C# 很陌生。我正在尝试使用以下方法检索列数:

SELECT count(*) FROM sys.columns 

您能否解释一下如何使用该命令并将其放入变量中。

4

7 回答 7

4

要连接到数据库,您可以使用SqlConnection该类,然后检索行数,您可以使用该Execute Scalar函数。来自 MSDN 的示例:

cmd.CommandText = "SELECT count(*) FROM sys.columns;";
Int32 count = (Int32) cmd.ExecuteScalar();

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection

于 2012-05-22T09:23:29.033 回答
4

您将需要ExecuteScalar像其他人所说的那样使用。此外,您将需要过滤您SELECTobject_id列以获取特定表中的列。

SELECT count(*) FROM sys.columns WHERE object_id = OBJECT_ID(N'table_name')

或者,您可能比熟悉ANSI 标准INFORMATION_SCHEMA视图以面向未来的跨 RDBMS 方式查找相同信息更糟糕。

于 2012-05-22T09:26:38.107 回答
2

您必须使用命令并取回标量变量:

SqlCommand cmd = new SqlCommand(sql, conn);
Int32 count = (Int32)cmd.ExecuteScalar();
于 2012-05-22T09:26:24.773 回答
1
string connectionString =
            "Data Source=(local);Initial Catalog=Northwind;"
            + "Integrated Security=true";

        // Provide the query string with a parameter placeholder.
        string queryString =
            "SELECT Count(*) from sys.columns";

        // Specify the parameter value.
        int paramValue = 5;

        // Create and open the connection in a using block. This
        // ensures that all resources will be closed and disposed
        // when the code exits.
        using (SqlConnection connection =
            new SqlConnection(connectionString))
        {
            // Create the Command and Parameter objects.
            SqlCommand command = new SqlCommand(queryString, connection);

            // Open the connection in a try/catch block. 
            // Create and execute the DataReader, writing the result
            // set to the console window.
            try
            {
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine("\t{0}",
                        reader[0]);
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }
于 2012-05-22T09:24:07.777 回答
1

使用 Executescalar() 获取单个元素。

 using (SqlConnection con = new SqlConnection(ConnectionString)) //for connecting to database
            {
                con.Open();
                try
                {
                    using (SqlCommand getchild = new SqlCommand("select count(*) from table1 ", con)) //SQL queries
                    {
                        Int32 count = (Int32)getchild.ExecuteScalar();
                     }
                }
             }
于 2012-05-22T09:24:52.420 回答
0

您需要在 System.Data.SqlClient 命名空间中使用 ADO .NET 函数。当您只想获得单个结果时,ExecuteScalar 是一种易于使用的方法。对于多个结果,您可以使用 SqlDataReader。

using System.Data.SqlClient;
string resultVar = String.Empty;
string ServerName="localhost";
string DatabaseName="foo";
        SqlConnection conn=new SqlConnection(String.Format("Data Source={0};Initial Catalog={1};Integrated Security=SSPI",ServerName,DatabaseName));
        SqlCommand cmd=new SqlCommand(Query,conn);
        try
        {
            conn.Open();
        }
        catch (SqlException se)
        {
            throw new InvalidOperationException(String.Format(
                "Connection error: {0} Num:{1} State:{2}",
                se.Message,se.Number, se.State));
        }
        resultVar = (string)cmd.ExecuteScalar().ToString();
        conn.Close();
于 2012-05-22T09:27:31.590 回答
0

利用ExecuteScalar

执行查询,并返回查询返回的结果集中第一行的第一列。其他列或行将被忽略。

Int32 colnumber = 0;
string sql = "SELECT count(*) FROM sys.columns";
using (SqlConnection conn = new SqlConnection(connString))
{
    SqlCommand cmd = new SqlCommand(sql, conn);
    try
    {
        conn.Open();
        colnumber = (Int32)cmd.ExecuteScalar();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}
于 2012-05-22T09:22:01.070 回答