C#连接SQL Server数据库

21 篇文章 0 订阅

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等字段错误时,就会有延时甚至死机的风险,所以超时写小一点。
        运行程序,点击按钮,可以看到:

  • 6
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值