【前言】
目前越來越多的工控軟體采用了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