user3173025
user3173025

Reputation:

Trying to pass database name and text to call a SQL command in different file

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

Upvotes: 0

Views: 51

Answers (2)

TheGeneral
TheGeneral

Reputation: 81503

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

Upvotes: 1

Malakiya sanjay
Malakiya sanjay

Reputation: 208

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);

Upvotes: 0

Related Questions