To insert data into a database using C#, you need to follow these steps:
Step 1 : Establish a connection to the database: You can use the SqlConnection class in C# to create a connection to the database. The connection string specifies the database to connect to, as well as any necessary authentication information.
Step 2: Open the connection: Before you can execute any queries, you need to open the connection to the database.
Step 3: Create a SqlCommand object: The SqlCommand object is used to execute queries against the database. You can create a SqlCommand object and specify the SQL query to execute.
Step 4: Execute the query: You can execute the SQL query using the ExecuteNonQuery method of the SqlCommand object.
Step 5: Close the connection: After you have finished executing queries, you should close the connection to the database.
Here is an example of how to insert data into a database using C#:
protected void btn_save_Click(object sender, EventArgs e)
{
string consString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(consString))
{
con.Open();
SqlCommand cmd = new SqlCommand("insert tbl_student(name,rollno) values('"+txt_name.Text+"','"+txt_roll_no.Text+"' ", con);
cmd.ExecuteNonQuery();
con.Close();
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Updated Successfully')", true);
return;
}
}
web.config
<connectionStrings>
<add name="constr" connectionString="Data Source=localhost;Initial Catalog=DATABSEBANE;UID=sa;PWD=123; providerName="System.Data.SqlClient" />
</connectionStrings>