Thứ Sáu, 27 tháng 12, 2013

2_Thực thi câu truy vấn SQL trên C#

1. Lấy ra họ tên và mã số sinh viên từ table sinh viên

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;



namespace ketnoiCSDL3
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionstring = "Data Source=PC1;Initial Catalog=demo1;Integrated Security=True";
            SqlConnection con = new SqlConnection(connectionstring);


            //Lay ve mot mang
            string sql = "select tensv,masv from sinhvien";
            SqlCommand cmd = new SqlCommand(sql, con);
            try
            {
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(reader[0].ToString() + " " + reader[1].ToString());
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                cmd.Dispose();
                con.Close();
            }
            Console.Read();
        }
    }
}

2. Lấy một giá trị trả về trong C#

 //Lay 1 gia tri tra ve
            string sql = "select tensv from sinhvien where masv='008'";
            SqlCommand cmd = new SqlCommand(sql, con);
            try
            {
                con.Open();
                string kq = cmd.ExecuteScalar().ToString(); // tra ve 1 gia tri
                Console.WriteLine(kq);

            }
            catch (SqlException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                cmd.Dispose();
                con.Close();
            }

3. Insert cơ sở dữ liệu trong C#

 //Them sinh vien vao table
            string sql = "insert into sinhvien values('008','Tran van X')";
            SqlCommand cmd = new SqlCommand(sql,con);
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                cmd.Dispose();
                con.Close();
            }
            //End of Them sinh vien vao table

Không có nhận xét nào:

Đăng nhận xét