Search code examples
c#console-applicationsqlclient

Getting tables name in Console application


I'm trying getting tables name in database, the connection is successful but the select Query give me (System.Data.SqlClient.SqlCommand) in the result. below my code.

SqlCommand cmd = new SqlCommand("select TABLE_NAME from DBNAME.TABLES");
Console.WriteLine(cmd);
string SelectQuery = "SELECT * FROM dbo.DBNAME";
SqlCommand a = new SqlCommand(SelectQuery);
Console.WriteLine(a); 

attach the output.enter image description here


Solution

  • First of all you must specify connection string

    SqlCommand cmd = new SqlCommand("select TABLE_NAME from DBNAME.TABLES", connection_string);
    

    then you must execute the command->

    using (SqlDataReader reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            Console.WriteLine(reader[0]);
        }
    }