35

Good day to all, I'm using Visual C# 2010 and MySQL Version 5.1.48-community. I hope you can help me with this code. I don't find it working on me. What am I missing?

string connString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connString);
conn.Open();
MySqlCommand comm = conn.CreateCommand();
comm.CommandText = "INSERT INTO room(person,address) VALUES(@person, @address)";
comm.Parameters.Add("@person", "Myname");
comm.Parameters.Add("@address", "Myaddress");
comm.ExecuteNonQuery();
conn.Close();

And when I try to compile it. It says:

Person column cannot be null

EDITED:

But when I try this code.

comm.CommandText = "INSERT INTO room(person,address) VALUES('Myname', 'Myaddress')";

But this code is prone to sql injection attack but it works, doesn't gives me an error.

EDITED:

I tried to use this. I found it here so I thought It would work but gives me this error

Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

Any idea?

    string a = "myname";
    MySqlCommand cmd = new MySqlCommand();
    cmd.Connection = conn;
    cmd.CommandText = "INSERT INTO room(person,address) VALUES(?,?)";
    //cmd.Prepare();

    cmd.Parameters.Add("person", MySqlDbType.VarChar).Value = a;
    cmd.Parameters.Add("address", MySqlDbType.VarChar).Value = "myaddress";
    cmd.ExecuteNonQuery(); // HERE I GOT AN EXCEPTION IN THIS LINE

Any help would be much appreciated.

EDITED: SOLVED I used this code:

cmd.CommandText = "INSERT INTO room(person,address) VALUES(?person,?address)";
cmd.Parameters.Add("?person", MySqlDbType.VarChar).Value = "myname";
cmd.Parameters.Add("?address", MySqlDbType.VarChar).Value = "myaddress";
cmd.ExecuteNonQuery();

Thanks SO!

Aleksandar
  • 1,163
  • 22
  • 41
Boy Karton
  • 565
  • 3
  • 9
  • 13
  • could you post the exact exception you are getting? Normaly you should use AddWithValue as every one else stated. Add is depreciated so you shouldn't use it – Rémi Apr 23 '13 at 14:01
  • There. I got an exception in `cmd.ExecuteNonQuery();` Yeah I know. You see I'm using Visual C# 2010 and I tried to use AddWithValue but It seems 2010 doesn't support it. Don't know if I'm right though. – Boy Karton Apr 23 '13 at 14:07
  • I curently work with vs2008 and I use it. At my college we had vs2010 and we were using AddWithValue – Rémi Apr 23 '13 at 14:16
  • Really? This comes out when I used AddWithValue. `MySql.Data.MySqlClient.MySqlParameterCollection' does not contain a definition for 'AddWithValue' and no extension method 'AddWithValue' accepting a first argument of type 'MySql.Data.MySqlClient.MySqlParameterCollection' could be found (are you missing a using directive or an assembly reference?)` – Boy Karton Apr 23 '13 at 14:21

9 Answers9

29

You may use AddWithValue method like:

string connString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connString);
conn.Open();
MySqlCommand comm = conn.CreateCommand();
comm.CommandText = "INSERT INTO room(person,address) VALUES(@person, @address)";
comm.Parameters.AddWithValue("@person", "Myname");
comm.Parameters.AddWithValue("@address", "Myaddress");
comm.ExecuteNonQuery();
conn.Close();

OR

Try with ? instead of @, like:

string connString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connString);
conn.Open();
MySqlCommand comm = conn.CreateCommand();
comm.CommandText = "INSERT INTO room(person,address) VALUES(?person, ?address)";
comm.Parameters.Add("?person", "Myname");
comm.Parameters.Add("?address", "Myaddress");
comm.ExecuteNonQuery();
conn.Close();

Hope it helps...

Aleksandar
  • 1,163
  • 22
  • 41
Rahul
  • 5,603
  • 6
  • 34
  • 57
  • I'm using Visual C# 2010 Express. The first one won't let me use AddWithValue.. And I already tried the second one.. Won't give me errors but won't insert to my database. – Boy Karton Apr 23 '13 at 11:26
  • 1
    this is so confusing... official doc says use `@` - https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-parameters.html - but it did not work for me, and only `?` did. – avs099 Jul 25 '18 at 15:24
6

Use the AddWithValue method:

comm.Parameters.AddWithValue("@person", "Myname");
comm.Parameters.AddWithValue("@address", "Myaddress");
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
5

I had the same issue -- Finally tried the ? sigil instead of @, and it worked.

According to the docs:

Note. Prior versions of the provider used the '@' symbol to mark parameters in SQL. This is incompatible with MySQL user variables, so the provider now uses the '?' symbol to locate parameters in SQL. To support older code, you can set 'old syntax=yes' on your connection string. If you do this, please be aware that an exception will not be throw if you fail to define a parameter that you intended to use in your SQL.

Really? Why don't you just throw an exception if someone tries to use the so called old syntax? A few hours down the drain for a 20 line program...

MySQL::MySQLCommand

Gerard ONeill
  • 3,914
  • 39
  • 25
4

Three things: use the using statement, use AddWithValue and prefix parameters with ? and add Allow User Variables=True to the connection string.

 string connString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
 using (var conn = new MySqlConnection(connString))
 {
      conn.Open();
      var comm = conn.CreateCommand();
      comm.CommandText = "INSERT INTO room(person,address) VALUES(@person, @address)";
      comm.Parameters.AddWithValue("?person", "Myname");
      comm.Parameters.AddWithValue("?address", "Myaddress");
      comm.ExecuteNonQuery();
  }

Also see http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx for more information about the command usage, and http://dev.mysql.com/doc/refman/5.1/en/connector-net-connection-options.html for information about the Allow User Variables option (only supported in version 5.2.2 and above).

L-Four
  • 13,345
  • 9
  • 65
  • 109
  • did you add AllowUserVariables=true to your connection string? – L-Four Apr 23 '13 at 11:24
  • Yes but it's not supported. – Boy Karton Apr 23 '13 at 11:31
  • did you do it like: ConnectionString = "DataSource=xx;Database=test;UserID=xx;Password=xx;PORT=xx;Allow Zero Datetime=True;allow user variables = true"; ? Maybe show your connection string... (it's supported as from version 5.2.2, which version do you have?) – L-Four Apr 23 '13 at 11:34
  • Here. I added Allow user Variables but it says not supported. connectionString="Server=localhost;Database=super;uid=root;password=root;Allow User Variables=true;" – Boy Karton Apr 23 '13 at 11:39
  • what mysql version are you using? – L-Four Apr 23 '13 at 11:45
  • I'm using Version 5.1.48-community. I don't have any clue what's wrong with my code. – Boy Karton Apr 23 '13 at 11:52
  • Allow User Variables is not supported in that version, see http://dev.mysql.com/doc/refman/5.1/en/connector-net-connection-options.html. I think you might need to upgrade. – L-Four Apr 23 '13 at 11:54
4

I was facing very similar problem while trying to insert data using mysql-connector-net-5.1.7-noinstall and Visual Studio(2015) in Windows Form Application. I am not a C# guru. So, it takes around 2 hours to resolve everything.

The following code works lately:

string connetionString = null;
connetionString = "server=localhost;database=device_db;uid=root;pwd=123;";

using (MySqlConnection cn = new MySqlConnection(connetionString))
{
    try
    {
        string query = "INSERT INTO test_table(user_id, user_name) VALUES (?user_id,?user_name);";
        cn.Open();
        using (MySqlCommand cmd = new MySqlCommand(query, cn))
        {
            cmd.Parameters.Add("?user_id", MySqlDbType.Int32).Value = 123;
            cmd.Parameters.Add("?user_name", MySqlDbType.VarChar).Value = "Test username";
            cmd.ExecuteNonQuery();
        }
    }
    catch (MySqlException ex)
    {
        MessageBox.Show("Error in adding mysql row. Error: "+ex.Message);
    }
}
arshovon
  • 13,270
  • 9
  • 51
  • 69
0
comm.Parameters.Add("person", "Myname");
DarkBee
  • 16,592
  • 6
  • 46
  • 58
0

What I did is like this.

String person;
String address;
person = your value;
address =your value;
string connString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
    MySqlConnection conn = new MySqlConnection(connString);
    conn.Open();
    MySqlCommand comm = conn.CreateCommand();
    comm.CommandText = "INSERT INTO room(person,address) VALUES('"+person+"','"+address+"')";
    comm.ExecuteNonQuery();
    conn.Close();
Barry
  • 1
  • 1
  • Can you add what your answer does differently please? Explaining what you did helps future readers understand faster and gets you more rep. – G_V Feb 12 '18 at 14:19
-1

Try adjusting the code at "SqlDbType" to match your DB type if necessary and use this code:

comm.Parameters.Add("@person",SqlDbType.VarChar).Value=MyName;

or:

comm.Parameters.AddWithValue("@person", Myname);

That should work but remember with Command.Parameters.Add(), you can define the specific SqlDbType and with Command.Parameters.AddWithValue(), it will try get the SqlDbType based on parameter value implicitly which can break sometimes if it can not implicitly convert the datatype.

Hope this helps.

  • I've tried doing this `cmd.Parameters.Add("@person", MySqlDbType.VarChar).Value = "myname";` and still same error. Don't know where I went wrong – Boy Karton Apr 23 '13 at 13:01
  • comm.Parameters.Add("@person",SqlDbType.VarChar).Value = TextBox1.Text; //See if the error still occurs like that. – user2310201 Apr 23 '13 at 13:43
  • Still doesn't work. I even tried to retyping all of it. Still the same error. Don't know where I went wrong. – Boy Karton Apr 23 '13 at 14:10
-2

try this it is working

 MySqlCommand dbcmd = _conn.CreateCommand();
    dbcmd.CommandText = sqlCommandString;
    dbcmd.ExecuteNonQuery();
    long imageId = dbcmd.LastInsertedId;
user3722956
  • 59
  • 2
  • 13