My goal is to extract the list of tables in a given data base, in truth one can carried out that with a simple request Sql, it is enough to carry out that:
But I do not find interesting, in a Windows or Web application , to process in this way, whereas we can do it differently, just by taking the connexion schema, it is more flexible and more elegant:
private DataTable GetListTablesFromDB()
{
SqlConnection conn = null;
try
{
conn = new SqlConnection(“My connection string here!”);
conn.Open();
DataTable schemaTable = conn.GetSchema(“Tables”);
return schemaTable;
}
catch (SqlException ex)
{
throw ex;
}
finally
{
conn.Close();
}
return null;
}
In the example precede I used a Sql connection, that goes only with the version ADO.net 2.0, if you use a previous version, you should then use a OleDb connection:
private DataTable GetListTablesFromDB ()
{
string strConn = "Provider=SQLOLEDB;Data Source=localhost;
Initial Catalog=Northwind;User ID=sa;Password=;";
OleDbConnection conn = null;
try
{
conn = new OleDbConnection(strConn);
conn.Open();
DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] {null, null, null, "TABLE"});
return schemaTable;
}
catch (OleDbException ex)
{
Trace.Write(ex.Message);
Response.Write(ex.Message);
}
finally
{
conn.Close();
}
return null;
}
Then we can post this list of tables in a combobox, for example :
private void TablesListFill()
{
try
{
this.TablesList.Items.Clear();
DataTable dtTablesList = this.GetListObjectFromDB("Tables");
for (int i = 0; i this.TablesList.Items.Add(dtTablesList.Rows[i][2].ToString());} catch (System.Exception ex) { throw ex; } }
Aucun commentaire:
Enregistrer un commentaire