Introduction
SqlConnection and SqlCommand are classes of a
connected architecture and found in the System.Data.SqlClient namespace. The SqlConnection
class makes a connection with the database. Further, this connection (database
connection) is used by the SqlCommand to work with that database. The SqlCommand class
is used to execute the SQL statements. Let's work with the SqlConnection and SqlCommand
classes with simple examples.
SqlConnection Class
Here, we will use two important methods of SqlConnection.
Open() : The open() method is used to open the Database
connection.
Close() : The close() method is used to close the Database
connection.
Look at the following code
- using System;
- using System.Data;
- using System.Data.SqlClient;
- namespace sqlconnectionANDsqlcommand
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void btnclick_Click(object sender, EventArgs e)
- {
- SqlConnection conn = new SqlConnection("Database=student;Server=.;user=sa;password=aaaaaaa");
- conn.Open(); // Open the connection
- // body
- // body
- conn.Close(); // Close the connection
- }
- }
- }
Add the following code to the application.
- private void btnclick_Click(object sender, EventArgs e)
- {
- // connection is opened. so if you click button then messagebox will be shown with the message "Open"
- SqlConnection conn = new SqlConnection("Database=student;Server=.;user=sa;password=aaaaaaa");
- conn.Open();
- MessageBox.Show(conn.State.ToString());
- conn.Close();
- }
- private void btnok_Click(object sender, EventArgs e)
- {
- // connection is not opened. so if you click button then messagebox will be shown with the message "Closed"
- SqlConnection conn = new SqlConnection("Database=student;Server=.;user=sa;password=aaaaaaa");
- MessageBox.Show(conn.State.ToString());
- }
SqlCommand Class
The main role of SqlCommand is to execute SQL statements.
SqlCommand Properties
CommandText: The commandText property is used to set the SQL statement.
Connection: This property is used to get connection to the database
source which is specified in SqlConnection.
SqlCommand Method
ExecuteNonQuery() : The
ExecuteNonQuery() method does not return any record. Which means we use
ExecuteNonQuery() in all operations with databases except retrieving records from a
database. It only returns the number of affected rows.
Now we use this method in our application. There is a database "student" and a
database "student_detail" which has no record. I am giving a simple example to
insert a record into database.
Take 3 labels, 3 textboxes and 1 button and arrange them as in the following figure.
mikepowertech mikepowertechPosted Jan 4, 2021, 6:47 AM
That is great post! Would be super to see the db and the source code project , if it is possible?