C#连接SQL Server数据库

来源:互联网 发布:php ext目录 编辑:程序博客网 时间:2024/05/21 19:44

C#连接SQL Server数据库

        这里简单介绍常见连接SQL Server数据库的办法。
        要连接的数据库是本地SQL Server,官方的Northwind数据库。
        在VS2010中创建一个窗体应用程序,添加一个按钮,其作用是点击后,验证连接数据库成功。
        编写按钮后台代码,如下:
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 CSharpConnectSQL{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void btnCSharpConnectSQL_Click(object sender, EventArgs e)        {            string strConnection = "Server=localhost;";            strConnection += "initial catalog=Northwind;";            strConnection += "user id=sa;";            strConnection += "password=123;";            strConnection += "Connect Timeout=5";            bool canConnectSQL = false;            using (SqlConnection objConnection = new SqlConnection(strConnection))            {                try                {                    objConnection.Open();                    canConnectSQL = true;                    objConnection.Close();                }                catch                { }                if (canConnectSQL)                    MessageBox.Show("数据库连接成功!", "Crazygolf Alert");                else                {                    MessageBox.Show("数据库连接失败!", "Crazygolf Alert");                }            }        }    }}
        请注意以下几点:
  •         Server属性值是数据库的地址,本地可使用localhost或者点(.),也可以键入IP地址。如需远程,应开通远程访问功能。
  •         initial catalog属性值是要连接的数据库的名称,这里用Northwind代替。
  •         user id和password无庸赘述。
  •         Connect Timeout属性值为连接超时时间。调用数据库Open()方法时,程序进入阻塞状态,期间根据我们写的连接字符串不断地打开数据库,如果网络不同或者Server等字段错误时,就会有延时甚至死机的风险,所以超时写小一点。
        运行程序,点击按钮,可以看到:

4 0
原创粉丝点击