Asım Gündüz
Asım Gündüz

Reputation: 1297

Insert into mysql table using c#

I'm trying to insert some data to my MySql table using C# but I'm facing some problems I've added the MySql.Data.MySqlClient reference.

I've gone through some tutorials on the web and I found some codes like cmd.Parameters.AddWithValue; however when I try to write this code it does not show up any idea why? It only shows .Add.

I've created a simple table 'inf' which has a id, name and surname where id is the primary key and it's on autoIncrement. My code is as follows:

string connString = "Server=localhost;Database=insertdeneme;Uid=****;Pwd=********;";
MySqlConnection mcon = new MySqlConnection(connString);
mcon.Open();

string cmdText = "INSERT INTO inf VALUES (null, @name, @surname)";
MySqlCommand cmd = new MySqlCommand(cmdText, mcon);
cmd.Parameters.Add("@name", txtname.Text);
cmd.Parameters.Add("@surname", txtsurname.Text);
cmd.ExecuteNonQuery();

The program compiles however when I press on the button I get the following error:

Column count doesn't match value count at row 1

When I remove the null from values I get:

Column 'name' cannot be null

So what do you think is the problem with the code?

Edited: I have one form, two text boxes and a button (txtname.text,txtsurname.text, btn.register). I added the mysql.data.mysqlclient reference.

I created a database using phpMyAdmin, and in my table I have id name and surname where id is primary and on auto increment with 11 digits and name surname are type of varchar with the limitation of 255 chars and the rest of the code are above.

What I also don't understand is why am I not able to use addwithvalue.

Error 1 '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?) C:\Users\FOREVER\documents\visual studio 2010\Projects\InsertInto1\InsertInto1\Form1.cs 63 32 InsertInto1

Upvotes: 2

Views: 17861

Answers (2)

jmail
jmail

Reputation: 6132

I think your giving id is autoincrement, if your mention the autoincrement means not mention the null value you should must remove the null,..

update:1

string cmdText= "INSERT INTO inf(name, surname) VALUES (@name, @surname)";
MySqlCommand cmd = new MySqlCommand(cmdText, mcon);
cmd.Parameters.AddWithValue("@name", TextBox1.Text);
cmd.Parameters.AddWithValue("@surname", TextBox2.Text);
cmd.ExecuteNonQuery();

Upvotes: 4

David
David

Reputation: 219047

id is the primary key and it's on autoIncrement

Then don't try to insert an id. Especially don't try to insert a null value into a primary key. Since you're only inserting data into two of the table's columns, specify those columns:

INSERT INTO inf (name, surname) VALUES (@name, @surname)

Upvotes: 3

Related Questions