C#连接SQL Server数据库
2015-03-29 10:59
134 查看
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等字段错误时,就会有延时甚至死机的风险,所以超时写小一点。
运行程序,点击按钮,可以看到:
相关文章推荐
- 用ASP.NET/C#连接Access和SQL Server数据库
- 用ASP.NET/C#连接Access和SQL Server数据库
- C# 连接SQL Server数据库的几种方式--server+data source等方式
- [原创]C#中使用ADO.NET连接SQL Server数据库,自动增长字段用作主键,处理事务时的基本方法
- C# 连接SQL Server数据库
- 用ASP.NET/C#连接Access和SQL Server数据库
- 用C#做一个与SQL server数据库连接的登录界面
- C#连接SQL SERVER数据库
- C#连接Access和SQL Server数据库
- C#连接SQL SERVER数据库的详细步骤!
- 用ASP.NET/C#连接Access和SQL Server数据库
- 用ASP.NET/C#连接Access和SQL Server数据库
- 用ASP.NET/C#连接Access和SQL Server数据库
- C#连接SQL Server数据库代码解析
- 一条C#连接SQL Server数据库写法
- 用ASP.NET/C#连接Access和SQL Server数据库
- C#连接SQL SERVER数据库的登录窗口
- 用ASP.NET/C#连接Access和SQL Server数据库
- C#代码连接SQL Server数据库
- android项目之连接数据库(eclipse(java)+soap协议+webservice服务(c#)+sql server数据库)