amish amish - 3 months ago 12
SQL Question

SqlCommand INSERT query does not insert data into database

I am working on visual studio 2013

In below code the

MessageBox.Show("Connected to database")
is shown correctly but the sql query is not inserted data into database table.

When I insert data manually then it insert with no problem. But unfortunately the data fails to insert on
button_click
command.

private void DataAdd_Load(object sender, EventArgs e)
{
try
{

conn= new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=Pathname;Integrated Security=True;Connect Timeout=30");
conn.Open();
MessageBox.Show("Connected to database");
cmd = new SqlCommand("INSERT INTO datains (name, dob, gender, occupation, height, weight, relation, polexpo) values('abc', '22-Aug-2001', 'Male', 'qwe2', '23', '431', 'qw23e', 'asqwed');",conn);

}
catch (Exception e1)
{
MessageBox.Show("Connection failed");
}
}


What I have done wrong here or anything I have missed ?

Answer

You have forgotten to execute query

cmd.ExecuteNonQuery();

also better to close the connection after work done

conn.Close();