I am a newbie to c#. I am trying to insert the values from the text box into the table in my database.
Table Name : address
Fields : name(varchar(50)), age(int), city(nchar(10))
When i try to retrieve the values from the database it is working perfectly. Here is my code. Please help me rectify it.
string s = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
SqlConnection a = new SqlConnection(s);
a.Open();
SqlCommand comm = new SqlCommand("INSERT INTO [address](name,age,city) VALUES(@na,@ag,@ci)");
string na = textBox1.Text;
int ag = int.Parse(textBox2.Text);
string ci = textBox3.Text;
comm.Parameters.Add("@na", System.Data.SqlDbType.VarChar,50).Value = na;
comm.Parameters.Add("@ag", System.Data.SqlDbType.Int).Value = ag;
comm.Parameters.Add("@ci", System.Data.SqlDbType.NChar,10).Value = ci;
comm.Connection = a;
comm.ExecuteNonQuery();
MessageBox.Show("okay");
a.Close();
The values are not reflected in the database.
try with this code :
string connectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand insertCommand = connection.CreateCommand())
{
insertCommand.CommandText = "INSERT INTO address(name,age,city) VALUES (@na,@ag,@ci)";
insertCommand.Parameters.Add("@na", na);
insertCommand.Parameters.Add("@ag", ag);
insertCommand.Parameters.Add("@ci", ci);
insertCommand.Connection.Open();
insertCommand.ExecuteNonQuery();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.