How to program to obtain database information

Source: Internet
Author: User
Obtain database information:
        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");
}
}
}
Get data table information:
        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));
}
}
}
Obtain field information:
        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));
}
}
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.