简体   繁体   中英

How to pass table name as parameter in OleDB?

private void button1_Click(object sender, EventArgs e)
{
        string tablename = label2.Text;
        string name = TextBox1.Text;
        DBconnection.savetodb(tablename, name);           

}

I call the method below from another form to save the name into a specific table. But it wont save into my table in database.

public static void savetodb(string tablename, string name)
{
        OleDbConnection connection = GetConnection();
        string query = String.Format("INSERT INTO {0} (Name) VALUES (@Name)", tablename);

        OleDbCommand cmd = new OleDbCommand(query, connection);
        cmd.Parameters.AddWithValue("@Name", name);

        try{
            connection.Open();
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex){
            Console.WriteLine("Exception catch", ex);
        }
        finally{
            myConnection.Close();
        }

Thanks for help.

You are not passing table name as a parameter, you are passing your @Name value as a parameter. You can't pass a table name as a parameter even if you want. Parameters only for values, not table or column names. You are just formatting your query based table name. As far as I see, your problem using named parameters. OleDb provider does not support named parameters.

From OleDbCommand.Parameters

The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:

SELECT * FROM Customers WHERE CustomerID = ?

Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.

Try it as;

string query = String.Format("INSERT INTO {0} (Name) VALUES (?)", tablename);
...
cmd.Parameters.AddWithValue("@name", name);

Also use using statement to dispose your OleDbConnection and OleDbCommand .

using(OleDbConnection connection = new GetConnection())
using(OleDbCommand cmd = con.CreateCommand())
{

}

And consider to use .Add method instead .AddWithValue . It may cause some problems. Read Can we stop using AddWithValue() already?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM