Reputation: 17
I have simple form which reads users name
,email
,and city
. I have created a database and a table with fields id
,name
,email
and city
. When I run the code I don't encounter any errors or exceptions,but unable to see the inserted data into table. Following is my code
SqlConnection con =
new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=F:\\Database1.mdf;Integrated Security=True");
con.Open();
SqlCommand cmd =
new SqlCommand("insert into tbl_insert values ( " + Convert.ToInt32(txtId.Text) + "," + "'" + txtName.Text + "'" + "," + "'" + txtEmail.Text + "'" + "," + "'" + txtboxCity.Text + "'" + ")", con);
cmd.ExecuteNonQuery();
con.Close();
I have attached my database screenshots. Database design:
This is output I get after running my code. Output with null value stored:
Upvotes: 0
Views: 140
Reputation: 39936
You should always use parameterized queries to avoid SQL Injection and get rids from quote problems:
SqlCommand cmd = new SqlCommand("insert into tbl_insert values (@id,@name,@Email,@City)");
cmd.Parameters.AddWithValue("@id", Convert.ToInt32(txtId.Text));
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
cmd.Parameters.AddWithValue("@City", txtboxCity.Text);
Although specify the type directly and use the Value
property is more better than AddWithValue
:
cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = txtName.Text;
Can we stop using AddWithValue() already?
Upvotes: 3
Reputation: 683
Try this
con.Open();
SqlCommand cmd = new SqlCommand(@"insert into tbl_insert values(@name,@email,@add)", con);
cmd.Parameters.AddWithValue("@name", txtname.Text);
cmd.Parameters.AddWithValue("@email", txtemail.Text);
cmd.Parameters.AddWithValue("@add", txtadd.Text);
cmd.ExecuteNonQuery();
con.Close();
i suspect the column id
is in Auto Number
if not just add another parameter to the query and cmd.Parameters
Upvotes: 1