检索表名
本文关键字:检索 | 更新日期: 2023-09-27 18:22:40
我正试图从正在使用的本地数据库中检索表的名称。
这是我尝试过的代码,但它从未通过foreach循环:
public void GetColumnNames()
{
SqlConnection con;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
con = new SqlConnection(Properties.Settings.Default.AlhusainSoundDBConnectionString);
List<string> colns = new List<string>();
try
{
con.Open();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
foreach (DataTable dt in ds.Tables)
{
colns.Add(dt.TableName);
Console.WriteLine(dt.TableName);
}
}
所以有人能建议我如何正确地进行吗
问候
要获得表名,需要使用INFORMATION_SCHEMA
USE <your_database_name>
GO
SELECT * FROM INFORMATION_SCHEMA.TABLES
除了打开到数据库的连接外,您还没有做任何事情。您的数据集尚未填充任何数据。我的方法是使用SqlCommand对象执行以下SQL语句并填充SqlDataReader
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
因此,C#代码可能看起来像这样:
string sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES";
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.AlhusainSoundDBConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
// do something with each table
string tableName= dr["TABLE_NAME"].ToString();
// OR
// string tableName = dr[0].ToString();
// OR
// string tableName = dr.GetString(0);
}
}
}