Select table using ListBox

0

I'm trying to read tables in an SQL statement. The names of the Tables, are pulled in a listbox.

Users will select the name of the table they want to view the data for, and in turn my method will read+visualize+export that table.

The issue is with the name of the table as a dynamic value. Initially I wrote the code in IronPython, and was ok.

Now I'm translating this to C# and I face a syntax issue (obviously, the server address/login posted here, are not the real ones).

The tables names are populated in listBox1 from a separate method.

private void rEADSELECTEDTABLE_Click(object sender, EventArgs e)
{
    string tableName = listBox1.GetItemText(listBox1.SelectedItem);
    MessageBox.Show(" Table Selected: " + tableName);

    try
    {
        string sqlConnectionString;
        myConnectionString = @"server=000.00.000.0;database=myDatabase;uid=myUser;password=myPassword";

        mySQL = new SqlConnection(myConnectionString);
        mySQL.Open();

        SqlCommand myCommand2 = new SqlCommand("SELECT * FROM @myTable", mySQL);
        SqlParameter param = new SqlParameter();
        param.ParameterName = "@myTable";
        param.Value = tableName;
        myCommand2.Parameters.Add(param);

        SqlDataAdapter myAdapter = new SqlDataAdapter();
        myAdapter.SelectCommand = myCommand2;

        DataSet dataSet = new DataSet();
        myAdapter.Fill(dataSet);

        List<string> rows = new List<string>();
        List<string> rowData = new List<string>();

        foreach (DataTable table in dataSet.Tables)
            foreach (DataRow row in table.Rows)
                foreach (DataColumn column in table.Columns)
                    if (row[column] != null)
                        rowData.Add(row[column].ToString());

        foreach (String s in rowData)
            Console.WriteLine(s);

        mySQL.Close();
    }
}

When I run the code I get this error:

System.Data.SqlClient.SqlException (0x80131904): Must declare the table variable "@myTable".

If I use a static table name, everything works well.

SqlCommand myCommand2 = new SqlCommand("SELECT * FROM TABLE_NAME", mySQL);
SqlDataAdapter myAdapter = new SqlDataAdapter();
myAdapter.SelectCommand = myCommand2;

Help greatly appreciated.

c#
sql
sql-server
tsql
ado.net
asked on Stack Overflow Apr 10, 2020 by alc • edited Apr 10, 2020 by abatishchev

1 Answer

0

you cannot use TableName as a parameter with SqlCommand

change the sql query, somthig like :

SqlCommand myCommand2 = new SqlCommand("SELECT * FROM " + tableName, mySQL);

OR

SqlCommand myCommand2 = new SqlCommand(string.Format("SELECT * FROM {0}", tableName), mySQL);

but be careful from sql injection attack !

another way is to work with dynamic sql query using stored procedure and send the table name as a parameter

answered on Stack Overflow Apr 10, 2020 by NajiMakhoul • edited Apr 10, 2020 by NajiMakhoul

User contributions licensed under CC BY-SA 3.0