M
Morris Neuman
Hi,
How do I check if a table exists in my database?
How do I check if a table exists in my database?
Allen Chen said:Hi Morris,
Here's the code for Access Database:
Aspx:
<asp:TextBox ID="TextBox1" runat="server" Text="Orders"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:Button ID="Button1"
runat="server" Text="Check" onclick="Button1_Click" />
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server">Yes the table
is in the database!</asp:LinkButton>
</ItemTemplate></asp:TemplateField></Columns>
</asp:GridView>
Aspx.cs:
protected void Button1_Click(object sender, EventArgs e)
{
using (OleDbConnection oc = new
OleDbConnection(ConfigurationManager.ConnectionStrings["Database1ConnectionS
tring"].ToString()))
{
oc.Open();
DataTable dt =oc.GetSchema("tables");
//The following code just shows the table on the page,
which can provide a direct vision of the data retrieved.
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
///////////////////////////
//The key here, to see if the table exists in the database
if you also want to check the views, please check dr[0] only.
string tablename = this.TextBox1.Text;
bool hasfound = false;
foreach (DataRow dr in dt.Rows)
{
if (dr[3].ToString() == "TABLE" &&
dr[2].ToString() == tablename)
{
Label1.Text = "The table " + tablename + " is in
the database";
this.GridView1.Columns[0].Visible = true;
hasfound = true;
break;
}
}
if (!hasfound)
{
Label1.Text = "The table " + tablename + " is NOT in
the database";
this.GridView1.Columns[0].Visible = false;
}
}
}
You can compare the above code with the code I provided in my previous
post, that is for Sql database. The main difference is to use the classes
under the System.Data.OleDb namespace instead of the classes under the
System.Data.SqlClient namespace. For example to use OleDbConnection instead
of SqlConnection. Another difference is the query. Though the query I
provided before can work for Access database it needs additional security
settings. To make it easier for you to test I used another way here, that
is to use OleDbConnection.GetSchema() method to get all the tables
information from the Access database. You can merge the above code into
your existing code. If you have any questions about the code please feel
free to ask.
Regards,
Allen Chen
Microsoft Online Support
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.