Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在控制台应用程序中获取表名_C#_Console Application_Sqlclient - Fatal编程技术网

C# 在控制台应用程序中获取表名

C# 在控制台应用程序中获取表名,c#,console-application,sqlclient,C#,Console Application,Sqlclient,我正在尝试在数据库中获取表名,连接成功,但select查询在结果中给出了(System.Data.SqlClient.SqlCommand)。下面是我的代码 SqlCommand cmd = new SqlCommand("select TABLE_NAME from DBNAME.TABLES"); Console.WriteLine(cmd); string SelectQuery = "SELECT * FROM dbo.DBNAME"; SqlCommand a = new SqlCom

我正在尝试在数据库中获取表名,连接成功,但select查询在结果中给出了(System.Data.SqlClient.SqlCommand)。下面是我的代码

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); 

附加输出。

您正试图使用
Console.WriteLine(a)打印
SqlCommand
类的完整限定名。当您试图打印任何类的对象时,将导致打印您引用的类的完整限定名

您必须使用
SqlDataAdapter
SqlCommand
的结果填充到
DataTable
中,如下所示:

SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select TABLE_NAME from DBNAME.TABLES", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dtTables = new DataTable();
da.Fill(dtTables);
for (int i = 0; i <= dtTables.Rows.Count - 1; i++)
{
    Console.WriteLine(dtTables.Rows[i][0]);
}
Console.ReadLine();   
SqlConnection con=新的SqlConnection(connectionString);
con.Open();
SqlCommand cmd=newsqlcommand(“从DBNAME.TABLES中选择表名”,con);
SqlDataAdapter da=新的SqlDataAdapter(cmd);
DataTable dtTables=新DataTable();
da.填写(数据表);

对于(inti=0;i,首先必须指定连接字符串

SqlCommand cmd = new SqlCommand("select TABLE_NAME from DBNAME.TABLES", connection_string);
然后必须执行命令->

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

当您执行Console.WriteLine(a)时,它将打印出类名,而不是运行SqlCommand查询。您需要执行并存储数据。然后您可以打印出表名

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

在我放置(Console.ReadLine();)时终止的输出不显示表名在我放置(Console.ReadLine();)时终止的输出不显示表名