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

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
xve
  • 48
  • 1
  • 6
  • What do you mean by _wont save_? You get any exception or error message? Did you debug your code as well? – Soner Gönül Nov 07 '14 at 07:52
  • The name is not save into my microsoft access table. i din't get any exception error message, yes i have debug my code. – xve Nov 07 '14 at 07:56

1 Answers1

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?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • i have retype my code above without changing anything and this time it work. i think there are something wrong with my visual studio 2013. but still thanks for your help, it improve my knowledge, I am still a beginner on C# :) – xve Nov 07 '14 at 20:04