如何编程得到数据库信息

获取数据库信息:
        public List<string> GetDatabase(string connectionString)
{
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("SELECT Name FROM Master.sys.SysDatabases WHERE dbid > 4 ORDER BY Name ", connectionString))
{
DataTable table = new DataTable();
try
{
sqlDataAdapter.Fill(table);

List<string> tables = new List<string>();
foreach (DataRow row in table.Rows)
{
tables.Add(row[0].ToString());
}
return tables;
}
catch
{
throw new ApplicationException("can not connect to server");
}
}
}
获取数据表信息:
        public List<string> GetTables(string connectionString, string db)
{
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(String.Format("SELECT name FROM {0}.sys.SysObjects WHERE (xtype = 'U' OR xtype = 'V') ORDER BY name", db), connectionString))
{
DataTable table = new DataTable();
try
{
sqlDataAdapter.Fill(table);

List<string> tables = new List<string>();
foreach (DataRow row in table.Rows)
{
tables.Add(row[0].ToString());
}
return tables;
}
catch
{
throw new ApplicationException(String.Format("can not connect to db {0} ", db));
}
}
}
获取字段信息:
        public DataTable GetFields(string connectionString, string db, string tableName)
{
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(string.Format("SELECT A.[name],[Type] =B.[name],A.[length] FROM {0}.sys.SysColumns AS A LEFT JOIN {0}.sys.SysTypes AS B ON A.[xtype]=B.[xusertype] WHERE A.[id] = OBJECT_ID('{0}.dbo.[{1}]')", db, tableName.Replace("'", "''")), connectionString))
{
DataTable table = new DataTable();
try
{
sqlDataAdapter.Fill(table);

return table;
}
catch
{
throw new ApplicationException(String.Format("can not connect to db {0}", db));
}
}
}
原文地址:https://www.cnblogs.com/zanxiaofeng/p/1687676.html