Breaking News

Cách kết nối C# tới SQL Server


Cách tạo chuỗi kết nối
Mở kết nối
Đóng kết nối
Có 5 cách kết nới cơ sở dữ liều từ C# với Sql
Server như sau:

using System.Data.SqlClient 

SqlConnection conic = null;

     1-   strConnection = "Data Source=DESKTOP-CR8PM8T\SQLEXPRESS; Initial Catalog=QLSV;

        Integrated Security = True";

     2 - strConnection = "Data Source=DESKTOP-CR8PM8T\SQLEXPRESS; Database=QLSV;

        Integrated Security = True";

     3-   strConnection = "Data Source=DESKTOP-CR8PM8T\SQLEXPRESS; Database=QLSV;

        Integrated Security = SSPI";

       4-  strConnection = "SERVER=DESKTOP-CR8PM8T\SQLEXPRESS; Database=QLSV;

        User Id = sa; Password=123";

      5-  string ketnoi = @"server =DESKTOP-CR8PM8T\SQLEXPRESS; Database = QLSV; User ID= sa; pwd= 123";

  Các mở kết nối và đóng kết nối sql
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient
;
//code kết nối cơ sở dữ liệu sql server vói c#
namespace knsdl
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 SqlConnection connec = null;
 string strconnec = @"server = DESKTOP-CR8PM8T\SQLEXPRESS; Database = QLSV; User id = sa; pwd=123";
 private void Form1_Load(object sender, EventArgs e)
        {}
private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                connec = new SqlConnection(strconnec);
                connec.Open();
                MessageBox.Show(" Mở kết nối thành công");

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }
private void button2_Click(object sender, EventArgs e)
        {
            if (connec!=null && connec.State == ConnectionState.Open)
            {
                connec.Close();
                MessageBox.Show("Đóng kết nối thành công");
            }
        }
    }
}


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