C#连接SQL Server

类别: C# 查看评论

步骤:

  1. 创建一个SqlConnection连接(注意连接字符串的写法),打开连接
  2. 创建一个SqlCommand,并设置Connection和CommandText
  3. 创建一个SqlDataAdapter,设置SelectCommand
  4. 创建DataSet,并填充 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            BindData();
        }
 
        private void BindData()
        {
            // Get connection string
            string connnString = GetConnectionString();
 
            // Create a SqlConnection to Northwind database
            using (SqlConnection conn = new SqlConnection(connnString))
            {
                // Open the connection
                conn.Open();
 
                // Create a SqlCommand to retrieve the data, and set the Connection
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "select * from dbo.Employees";
                cmd.Connection = conn;
 
                // Create a SqlDataAdapter, and set SelectCommand to the SqlCommand
                SqlDataAdapter adapter = new SqlDataAdapter();
                adapter.SelectCommand = cmd;
 
                // Crate a DataSet, and fill it with adapter
                DataSet dataset = new DataSet();
                adapter.Fill(dataset, "employees");
 
                dataGridView1.DataSource = dataset.Tables["employees"];
 
                // Close the connection
                conn.Close();
            }
        }
 
        private string GetConnectionString()
        {
            //return @"server=qbox\sqlexpress;database=northwind;trusted_connection=sspi";
            return @"Data Source=qbox\sqlexpress;Initial Catalog=Northwind;Integrated Security=SSPI";
        }
    }
}

 

参考:

[1] SqlConnection: http://msdn.microsoft.com/zh-cn/library/system.data.sqlclient.sqlconnection.aspx
[2] SqlCommand: http://msdn.microsoft.com/zh-cn/library/system.data.sqlclient.sqlcommand.aspx
[3] DataAdapter: http://msdn.microsoft.com/zh-cn/library/system.data.common.dataadapter.aspx
[4] DataSet: http://msdn.microsoft.com/zh-cn/library/system.data.dataset.aspx

发表评论