首页 > 数据库 >C#获得Access数据库中的表名,以及根据表名获取字段名

C#获得Access数据库中的表名,以及根据表名获取字段名

时间:2023-01-05 11:34:47浏览次数:50  
标签:string C# Access int DataRow 表名 new null conn

/// <summary>
/// 返回Mdb数据库中所有表表名
/// </summary>
public string[] GetShemaTableName(string database_path, string database_password)
{
try
{
//获取数据表
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:DataBase Password='" + database_password + "Data Source=" + database_path;
conn.Open();
DataTable shemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
int n = shemaTable.Rows.Count;
string[] strTable = new string[n];
int m = shemaTable.Columns.IndexOf("TABLE_NAME");
for (int i = 0; i < n; i++)
{
DataRow m_DataRow = shemaTable.Rows[i];
strTable[i] = m_DataRow.ItemArray.GetValue(m).ToString();
}
return strTable;
}
catch (OleDbException ex)
{
MessageBox.Show("指定的限制集无效:/n" + ex.Message);
return null;
}
finally
{
conn.Close();
conn.Dispose();
}
}

/// <summary>
/// 返回某一表的所有字段名
/// </summary>
public string[] GetTableColumn(string database_path,string varTableName)
{
DataTable dt = new DataTable();
try
{
conn = new OleDbConnection();
conn.ConnectionString = "Provider = Microsoft.Jet.OleDb.4.0;Data Source=" + database_path;
conn.Open();
dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, varTableName, null });
int n = dt.Rows.Count;
string[] strTable = new string[n];
int m = dt.Columns.IndexOf("COLUMN_NAME");
for (int i = 0; i < n; i++)
{
DataRow m_DataRow = dt.Rows[i];
strTable[i] = m_DataRow.ItemArray.GetValue(m).ToString();
}
return strTable;
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}

标签:string,C#,Access,int,DataRow,表名,new,null,conn
From: https://blog.51cto.com/kenkao/5989748

相关文章