0% found this document useful (0 votes)
25 views

Them Xoa Sua Dung Execute Non Query

The document describes code for adding a new class (Lop) to a database table. It includes a stored procedure to insert Lop data if the class ID does not already exist. The C# code calls this stored procedure, passing the class object and its attributes. It opens a database connection, executes the stored procedure, closes the connection, and returns the result.

Uploaded by

Tăng Lương
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Them Xoa Sua Dung Execute Non Query

The document describes code for adding a new class (Lop) to a database table. It includes a stored procedure to insert Lop data if the class ID does not already exist. The C# code calls this stored procedure, passing the class object and its attributes. It opens a database connection, executes the stored procedure, closes the connection, and returns the result.

Uploaded by

Tăng Lương
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Th tc

CREATE PROC [dbo].[Lop_Them] @MaLop varchar(10), @TenLop nvarchar(50), @SoSV int AS IF NOT EXISTS (SELECT MaLop FROM Lop WHERE MaLop=@MaLop) BEGIN INSERT INTO Lop (MaLop, TenLop, SoSV) VALUES (@MaLop, @TenLop, @SoSV) END

Lop.cs
public static int Them(Lop lop) { // 1. Tao ket noi Connection using (SqlConnection cnn = Helper.GetSqlConnection()) { // 2. Tao cmd Command SqlCommand cmd = cnn.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "Lop_Them"; // 3. Gan tham so cmd.Parameters .Add("@MaLop", SqlDbType.VarChar, 10) .Value = lop.MaLop; cmd.Parameters .Add("@TenLop", SqlDbType.NVarChar, 50) .Value = lop.TenLop; cmd.Parameters .Add("@SoSV", SqlDbType.Int) .Value = lop.SoSV; // 4. Mo ket noi cnn.Open(); // 5. Thuc thi truy van int rs = cmd.ExecuteNonQuery(); // 6. Dong ket noi cnn.Close(); // 7. Xu ly ket qua tra ve return rs;

} }

Program.cs
static void Main(string[] args) { // Tao du lieu Lop data = new Lop(); data.MaLop = "CTK31"; data.TenLop = "CNTT K31"; data.SoSV = 100; // Goi phuong thuc int rs = Lop.Them(data); if (rs > 0) Console.WriteLine("Them thanh cong"); else Console.WriteLine("Khong them duoc"); }

You might also like