实现给定一个数据库连接得到数据库下所有的数据表
使用OleDb可以满足这种需要
using System;
using System.Xml;
using System.Data;
using System.Collections;
using System.Data.OleDb;
namespace Generator
{
/// <summary>
/// DBAccess 的摘要说明。
/// </summary>
public class DBAccess
{
public DBAccess()
{
}
private static string ConStr = "";
private static string ConString
{
get
{
if(ConStr == "")
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load("ServerConfig.xml");
string userid = doc.SelectSingleNode("ServerConfig/UserId").InnerText;
string password = doc.SelectSingleNode("ServerConfig/PassWord").InnerText;
string servername = doc.SelectSingleNode("ServerConfig/ServerName").InnerText;
string database = doc.SelectSingleNode("ServerConfig/DataBase").InnerText;
ConStr = "User ID = " + userid + ";Data Source = " + servername + ";Initial Catalog = " + database + ";Provider = SQLOLEDB.1;password = " + password;
}
catch(Exception ex)
{
throw ex;
}
}
return ConStr;
}
}
private static OleDbConnection Con = new OleDbConnection(DBAccess.ConString);
public static OleDbConnection MyConnection
{
get
{
if(Con == null)
{
Con = new OleDbConnection(ConString);
}
return Con;
}
}
/// <summary>
/// 返回所有表
/// </summary>
/// <returns></returns>
public static DataTable GetAllTables()
{
DataTable dt = new DataTable();
try
{
Con.Open();
dt = Con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null,"Table"});
}
catch(Exception ex)
{
throw ex;
}
finally
{
Con.Close();
}
return dt;
}
/// <summary>
/// 返回指定表的结构
/// </summary>
/// <param name="varTableName"></param>
/// <returns></returns>
public static DataTable GetTheTable(string varTableName)
{
DataTable dt = new DataTable();
DataSet ds = new DataSet();
OleDbDataAdapter Odb = new OleDbDataAdapter("select * from " + varTableName,Con);
try
{
Con.Open();
Odb.FillSchema(ds,SchemaType.Source,varTableName);
}
catch(Exception ex)
{
throw ex;
}
finally
{
Con.Close();
}
return ds.Tables[varTableName];
}
}
}
配置文件
<?xml version="1.0" encoding="utf-8" ?>
<ServerConfig>
<ServerName>localhost</ServerName>
<DataBase>yourdb</DataBase>
<UserId>sa</UserId>
<PassWord>yourpwd</PassWord>
</ServerConfig>
比如说,用一个CheckBoxList来显示所有的表
调用如下:
foreach(DataRow dr in DBAccess.GetAllTables().Rows)
{
this.checkedListBox1.Items.Add(dr["Table_Name"].ToString());
}