c#获得目标服务器中所有数据库名、表名、列名的实现代码
/// <summary>
/// 获得目标服务器所有数据库名
/// </summary>
/// <param name="servername"></param>
/// <param name="username"></param>
/// <param name="password"></param>
public void getdatabasenamelist(string servername, string username, string password)
{
sqldmo.application sqlapplication = new sqldmo.applicationclass();
sqldmo.sqlserver sqlserver = new sqldmo.sqlserverclass();
sqlserver.connect(servername, username, password); // 连接服务器
foreach (sqldmo.database databbase in sqlserver.databases)
{
if (databbase.name != null)
{
this.databasetreeview.nodes.add(databbase.name);
getdatabasetablelist(servername, username, password, databbase.name);
}
}
}
/// <summary>
/// 加载数据库中表
/// </summary>
/// <param name="servername">服务器名</param>
/// <param name="username">用户名</param>
/// <param name="password">密码</param>
/// <param name="databasename">数据库名</param>
private void getdatabasetablelist(string servername, string username, string password, string databasename)
{
sqldmo.sqlserver server = new sqldmo.sqlserverclass();
//连接到服务器
server.connect(servername, username, password);
//对所有的数据库遍历,获得指定数据库
for (int i = 0; i < server.databases.count; i++)
{
//判断当前数据库是否是指定数据库
if (server.databases.item(i + 1, "dbo").name == databasename)
{
//获得指定数据库
sqldmo._database db = server.databases.item(i + 1, "dbo");
//获得指定数据库中的所有表
for (int j = 0; j < db.tables.count; j++)
{
this.databasetreeview.nodes[i].nodes.add(db.tables.item(j + 1, "dbo").name);
}
}
}
}
/// <summary>
/// 获得表中所有列名
/// </summary>
/// <param name="servername">服务器名</param>
/// <param name="username">用户名</param>
/// <param name="password">密码</param>
/// <param name="tablename">表名</param>
/// <param name="databasename">数据库名</param>
/// <returns></returns>
public string getrowlistfromtable(string servername, string username, string password, string tablename, string databasename)
{
string result = string.empty;
string connectionstring = string.empty;
connectionstring += "server=" + servername;
connectionstring += ";pwd=" + password;
connectionstring += ";uid=" + username;
connectionstring += ";database=" + databasename;
string commandstring = string.empty;
commandstring += "select name from syscolumns where id=object_id('";
commandstring += tablename;
commandstring += "')";
sqlconnection sqlconnection = new sqlconnection(connectionstring);
sqlcommand sqlcommand = new sqlcommand(commandstring, sqlconnection);
sqldataadapter dataadapter = new sqldataadapter(commandstring, sqlconnection);
dataset dataset = new dataset();
dataadapter.fill(dataset);
datatable datatable = dataset.tables[0];
// datatable datatable = sqlconnection.getschema("tables");
foreach (datarow row in datatable.rows)
{
result += row[0].tostring() + "-";
}
if (result != null)
{
return result;
}
else
{
return "0";
}
}