编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

C#(C sharp)连接MSSQL数据库实测(c#连接数据库的步骤)

wxchong 2024-06-30 10:10:35 开源技术 32 ℃ 0 评论

【前言】

目前越来越多的工控软件采用了C#作为开发平台或脚本程序,比如易控。C#的编程平台常有Visual Studio、SharpDevelop、SlickEdit等等,其中SharpDevelop编程软件因小而精悍深有一般入门者的喜欢,可以下面网址下载:

http://honeytree.ysepan.com/

【测试】

安装完毕SharpDevelop后,我们测试一下与MSSQL的连接。

首先新建一个解决方案,测试C#

在设计中,找到一个按钮

点击按钮

进入代码区间

注意前面声明:

using System.Data.SqlClient; 才能使用数据库命令。

按钮代码如下:

因为这里采用的windows自带的,无需密码。

且有转义字符,要增加"\"。

void Button1Click(object sender, EventArgs e)
{


const string connStr = "Data Source = DESKTOP-S26IOEH\\WINCC ; Initial Catalog = master ; Integrated Security = True";

SqlConnection conn = null;

try
{
conn =
new SqlConnection(connStr);

//打开数据库连接
conn.
Open();
MessageBox.Show("数据库连接成功!");
}
catch(Exception ex)
{
MessageBox.Show("数据库连接失败!" + ex.Message);
}
finally
{
if (conn != null)
{
//关闭数据库连接
conn.
Close();
}
}
}

测试:

备注:通过UDL实现数据源的获得,然后转换为C#能够识别的:

[oledb]

; Everything after this line is an OLE DB initstring

Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=master;Data Source=DESKTOP-S26IOEH\WINCC

转换后:

Data Source = DESKTOP-S26IOEH\\WINCC ; Initial Catalog = master ;Integrate d Security = True

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表