C Method for Getting All SQL Server Database Names

  • 2021-07-24 11:42:41
  • OfStack

This article example shows how C # gets the names of all SQL Server databases. Share it for your reference. The details are as follows:

Connect to the master library and execute select name from master.. sysdatabases.

sp_helpdb can also list data names, but not all of them. sp_helpdb will find out the corresponding database according to the current user role, while sysdatabases table can find out all database information as long as it has permission to access the table.

By default, in addition to the model database, several of the six databases provided by sqlserver may have guest users.
exec sp_helpdb gets a record of the databases that the current user has access to (including several guest access databases by default).
Any user (as long as they can connect to sqlserver) who queries the table sysdatabases in the master database can get all the database names, because the guest user of that table cannot be deleted.


/// <summary>
///  Take all database names , Add to lvDB
/// </summary>
/// <returns></returns>
private ArrayList GetAllDataBase()
{
 ArrayList DBNameList = new ArrayList();
 SqlConnection Connection = new SqlConnection(
  String.Format("Data Source={0};Initial Catalog=master;User ID={1};PWD={2}","(local)","sa","adminwinter"));
 DataTable DBNameTable = new DataTable();
 SqlDataAdapter Adapter = new SqlDataAdapter("select name from master..sysdatabases", Connection);
 lock (Adapter)
 { 
  Adapter.Fill(DBNameTable);
 }
 foreach (DataRow row in DBNameTable.Rows)
 {
  DBNameList.Add(row["name"]);
 }
 return DBNameList;
}

I hope this article is helpful to everyone's C # programming.


Related articles: