How to pass table name as parameter in OleDB?

耗尽温柔 提交于 2019-12-11 13:08:34

问题


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.


回答1:


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?



来源:https://stackoverflow.com/questions/26796523/how-to-pass-table-name-as-parameter-in-oledb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!