检索SQL表中的列数 - C#

时间:2012-05-22 09:20:19

标签: c# .net sql sql-server ado.net

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

SELECT count(*) FROM sys.columns 

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

7 个答案:

答案 0 :(得分: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

答案 1 :(得分:4)

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

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

或者,您可能会比熟悉ANSI-standard INFORMATION_SCHEMA views更难以在面向未来的跨RDBMS方式中找到相同的信息。

答案 2 :(得分:2)

您必须使用命令并检索标量变量:

SqlCommand cmd = new SqlCommand(sql, conn);
Int32 count = (Int32)cmd.ExecuteScalar();

答案 3 :(得分: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();
        }

答案 4 :(得分: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();
                     }
                }
             }

答案 5 :(得分: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);
    }
}

答案 6 :(得分: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();