经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » MS SQL Server » 查看文章
SQL Server创建连接代码示例
来源:jb51  时间:2019/3/12 10:16:18  对本文有异议

使用SqlConnection连接到SQL Server 2012

示例如下:

(1). 利用SqlConnection创建连接

  1. public SQLServerAPI(string str_ip, string str_db, string str_user, string str_pwd)
  2. {
  3. m_strIp = str_ip;
  4. m_strDb = str_db;
  5. m_strUser = str_user;
  6. m_strPwd = str_pwd;
  7. //SQLServer身份验证
  8. m_strConnection = @"Data Source=" + m_strIp;
  9. m_strConnection += @";Initial Catalog=" + m_strDb;
  10. m_strConnection += @";UID=" + m_strUser + ";PWD=" + m_strPwd;
  11. m_strConnection += ";Connection Timeout=10;Pooling=true;Max Pool Size=100";
  12. //Windows身份验证
  13. //m_strConnection =
  14. @"server=localhost\SQLEXPRESS;database=SQL2012Db;Trusted_Connection=SSPI;";
  15. DisConnect();
  16. m_Transaction = null;
  17. m_SqlConnection = new SqlConnection(m_strConnection);
  18. }

(2). 调用Open方法,以建立与服务器的会话。

  1. /// <summary>
  2. /// 尝试连接数据库
  3. /// </summary>
  4. private bool Connect()
  5. {
  6. if (m_SqlConnection == null)
  7. return false;
  8. try
  9. {
  10. m_SqlConnection.Open();
  11. }
  12. catch (Exception e)
  13. {
  14. Debug.WriteLine(e.Message);
  15. return false;
  16. }
  17. return true;
  18. }

(3). 调用Close()方法终止会话

  1. private bool DisConnect()
  2. {
  3. if (m_SqlConnection == null)
  4. return true;
  5. try
  6. {
  7. m_SqlConnection.Close();
  8. }
  9. catch (Exception e)
  10. {
  11. Debug.WriteLine(e.Message);
  12. return false;
  13. }
  14. return true;

许多程序员都使连接一直处于打开状态,直到程序结束为止,这通常会浪费服务器资源。与这种打开一次,永不关闭的方式相比,使用连接池,在需要时打开和关闭连接要更加高效。

如下所示,我们封装一个执行SQL存储过程的函数:

  1. /// <summary>
  2. /// 执行返回查询结果的存储过程
  3. /// </summary>
  4. /// <param name="procname">存储过程名?</param>
  5. /// <param name="param">参数。函数正常返回时,所有类型为out的参数值也在对应位置上</param>
  6. /// <param name="result">返回查询的结果</param>
  7. /// <returns>0正确,其他错误</returns>
  8. public int ExecQueryStoreProc(string procname, ref SqlParameter[] param, out DataTable result)
  9. {
  10. if (!Connect())
  11. {
  12. result = null;
  13. return -1;
  14. }
  15. try
  16. {
  17. SqlCommand command = new SqlCommand(procname, m_SqlConnection);
  18. command.CommandType = CommandType.StoredProcedure;
  19. if (m_Transaction != null)
  20. command.Transaction = m_Transaction;
  21. SqlParameter rvalue = command.Parameters.Add(new SqlParameter("RETURN_VALUE", SqlDbType.Int));
  22. rvalue.Direction = ParameterDirection.ReturnValue;
  23. if (param != null)
  24. command.Parameters.AddRange(param);
  25. result = new DataTable();
  26. SqlDataReader reader = command.ExecuteReader();
  27. if (reader.HasRows)
  28. result.Load(reader);
  29. return Convert.ToInt32(command.Parameters["RETURN_VALUE"].Value);
  30. }
  31. catch (Exception)
  32. {
  33. result = null;
  34. return -1;
  35. }
  36. finally
  37. {
  38. DisConnect();
  39. }
  40. }

上述过程就是在需要时打开和关闭连接的实现方式,另外finally块始终调用Close()方法,这并不会造成问题或者过多地浪费资源,而且能确保关闭连接。

以上所述是小编给大家介绍的SQL Server创建连接代码示例详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对w3xue网站的支持!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号