C# 在控制台应用程序中获取表名
我正在尝试在数据库中获取表名,连接成功,但select查询在结果中给出了(System.Data.SqlClient.SqlCommand)。下面是我的代码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
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();)时终止的输出不显示表名