C#获取所有SQL Server数据库名称的方法
用C#获取所有SQL Server数据库名称 可能需要用户的权限,注意安全
using System;
using System.Collections.Generic;using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
namespace AliWorkbenchProgram
{
class ClassSqlDataBaseOp
{
public static string showLog = "";
/// <summary>
/// 取所有数据库名称
/// </summary>
/// <returns></returns>
public static void GetAllDbName()
{
ArrayList dbNameList = new ArrayList();
DataTable dbNameTable = new DataTable();
string strConnection = "server=localhost;database=master; uid=sa;pwd=123456;Enlist=true";
SqlConnection conn = new SqlConnection(strConnection);
conn.Open();
showLog += "\r\n" + string.Format("连接数据库成功:{0}", conn.Database);
SqlDataAdapter adapter = new SqlDataAdapter("select name from master..sysdatabases", conn);
lock (adapter)
{
adapter.Fill(dbNameTable);
}
showLog += "\r\n" + string.Format("当前数据库总计: {0} 个", dbNameTable.Rows.Count);
foreach (DataRow row in dbNameTable.Rows)
{
dbNameList.Add(row["name"]);
showLog += "\r\n" + string.Format("数据库名称:{0}", row["name"]);
}
conn.Close();
}
}
}