1

Here in the code I am trying to retrieve information from a database and store it in a table. In query i have used a variable to specify a table, i am doing so because i want to use this single piece of code to retrieve information from various tables based on which table name the variable "a" contain but when i am executing this it's throwing me an exception. please help...

MyOleDbConnection.Open();
string a = "login";
string query = string.Format("select Email,Username,PhoneNo,Department from '{1}' where Email='{0}'", editrecordtextBox.Text,a);
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter();
da = new OleDbDataAdapter(query, MyOleDbConnection.vcon);
da.Fill(dt);

Note- this is just the part of the code, the exception is occuring in this code only.

3
  • 4
    Whats the exception message? What database are you using? Probable cause is single quote around table name in your query. Try to remove it. Commented May 4, 2013 at 17:41
  • i am using ms-access as my database. Commented May 4, 2013 at 17:43
  • 1
    thanks man it worked after removing the quotes.... Commented May 4, 2013 at 17:45

2 Answers 2

3

Your code is in fact working correctly.

First of all, remove your single quotes around the table name. These mark a text, not an identifier or name.

I can imagine that login is a reseverd name you cannot use as plain text in your SQL. Depending on the database you can quote your tablename so it is recognizes as a name, not an reserved word.

For SQL-Server it would be done with [ and ]:

string query = string.Format("select Email,Username,PhoneNo,Department from [{1}] where Email='{0}'", editrecordtextBox.Text,a);

If you would give us your database, we could help.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks man, but its working fine after removing the single quotes.
0

the way that tested and Worked is something like Below as you see the Table Name is Variable Form i Make a query with concatenate 3 section together

string query = "SELECT TOP 1 * FROM M" + TableName.ToString() + " ORDER BY ID 
DESC";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.