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 '.'

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

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

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • I'm a noob, and yeah that is what i'm trying to do. so what i'm doing is correct yeah? –  Feb 21 '20 at 06:22
  • 1
    @HasaraJayasinghe yes it should work if corrected. however try to use Parameterised queries. https://stackoverflow.com/questions/7505808/why-do-we-always-prefer-using-parameters-in-sql-statements – TheGeneral Feb 21 '20 at 06:29
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);
Malakiya sanjay
  • 208
  • 2
  • 12