0

I'm calling the following code:

public static bool checkDuplicateProducts(string item1, string item2)
{
    // new connection
    SqlConnection con = new SqlConnection(stringCon);

    // adapter query
    SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM '" + item1 + "' WHERE ProductCode='" + item2 + "'", con);

    DataTable dt = new DataTable();
    sda.Fill(dt);

    if (dt.Rows.Count >= 1)
    {
        return true;
    }
    else
    {
        return false;
    }
}

from this:

string tableName = "Product";
else if(Functions.checkDuplicateProducts(tableName, textBox2.Text) == true)
{
       MessageBox.Show("The id is already available", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

I get this error when doing so:

System.Data.SqlClient.SqlException: 'Incorrect syntax near ' Product '.'

2 Answers 2

1

Your table shouldn't be single quoted i.e SELECT * FROM table_name

"SELECT * FROM '" + item1 + "'

Should be

"SELECT * FROM " + item1 + "

However, you should really be using parameterised queries in general, lest you be on the wrong end of an sql injection attack

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

2 Comments

I'm a noob, and yeah that is what i'm trying to do. so what i'm doing is correct yeah?
@HasaraJayasinghe yes it should work if corrected. however try to use Parameterised queries. stackoverflow.com/questions/7505808/…
0

Select * from Table Name you Should by Not Accepted c# for the query in 'Table Name'

REPLACE THE CODE

  SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM " + item1 + " WHERE ProductCode='" + item2 + "'", con);

Comments

Your Answer

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