C#使用SqlConnection連接到SQL Server的代碼示例

這篇文章主要介紹了C#使用SqlConnection連接到SQL Server的代碼示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨着小編來一起學習學習吧

使用SqlConnection連接到SQL Server 2012

示例如下:

(1). 利用SqlConnection創建連接

public SQLServerAPI(string str_ip, string str_db, string str_user, string str_pwd)
{
 m_strIp = str_ip;
 m_strDb = str_db;
 m_strUser = str_user;
 m_strPwd = str_pwd;
   
 //SQLServer身份驗證
 m_strConnection = @"Data Source=" + m_strIp;
 m_strConnection += @";Initial Catalog=" + m_strDb;
 m_strConnection += @";UID=" + m_strUser + ";PWD=" + m_strPwd;
 m_strConnection += ";Connection Timeout=10;Pooling=true;Max Pool Size=100";
 
 //Windows身份驗證
 //m_strConnection = 
    @"server=localhost\SQLEXPRESS;database=SQL2012Db;Trusted_Connection=SSPI;";
   
 DisConnect();
 
 m_Transaction = null;
 m_SqlConnection = new SqlConnection(m_strConnection);
}

(2). 調用Open方法,以建立與服務器的會話。

/// <summary>
/// 嘗試連接數據庫
/// </summary>
private bool Connect()
{
 if (m_SqlConnection == null)
  return false;
 
 try
 {
  m_SqlConnection.Open();
 }
 catch (Exception e)
 {
  Debug.WriteLine(e.Message);
  return false;
 }
  return true;
}

(3). 調用Close()方法終止會話

private bool DisConnect()
{
 if (m_SqlConnection == null)
  return true;
 
 try
 {
  m_SqlConnection.Close();
 }
 catch (Exception e)
 {
  Debug.WriteLine(e.Message);
  return false;
 }
 return true;

許多程序員都使連接一直處於打開狀態,直到程序結束爲止,這通常會浪費服務器資源。與這種打開一次,永不關閉的方式相比,使用連接池,在需要時打開和關閉連接要更加高效。

如下所示,我們封裝一個執行SQL存儲過程的函數:

/// <summary>
/// 執行返回查詢結果的存儲過程
/// </summary>
/// <param name="procname">存儲過程名?</param>
/// <param name="param">參數。函數正常返回時,所有類型爲out的參數值也在對應位置上</param>
/// <param name="result">返回查詢的結果</param>
/// <returns>0正確,其他錯誤</returns>
public int ExecQueryStoreProc(string procname, ref SqlParameter[] param, out DataTable result)
{
	if (!Connect())
	{
		result = null;
		return -1;
	}
 
	try
	{
		SqlCommand command = new SqlCommand(procname, m_SqlConnection);
		command.CommandType = CommandType.StoredProcedure;
 
		if (m_Transaction != null)
			command.Transaction = m_Transaction;
 
		SqlParameter rvalue = command.Parameters.Add(new SqlParameter("RETURN_VALUE", SqlDbType.Int));
		rvalue.Direction = ParameterDirection.ReturnValue;
 
		if (param != null)
			command.Parameters.AddRange(param);
 
		result = new DataTable();
		SqlDataReader reader = command.ExecuteReader();
		if (reader.HasRows)
			result.Load(reader);
 
		return Convert.ToInt32(command.Parameters["RETURN_VALUE"].Value);
	}
	catch (Exception)
	{
		result = null;
		return -1;
	}
	finally
	{
		DisConnect();
	}
}

上述過程就是在需要時打開和關閉連接的實現方式,另外finally塊始終調用Close()方法,這並不會造成問題或者過多地浪費資源,而且能確保關閉連接。

以上所述是小編給大家介紹的SQL Server創建連接代碼示例詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對神馬文庫網站的支持!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章