C#使用SqlConnection连接到SQL Server的代码示例
- 作者: 熊宝121
- 来源: 51数据库
- 2020-08-07
这篇文章主要介绍了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创建连接代码示例详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。
推荐阅读
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
热点文章
团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
0
使用 MSBuild.exe 在发布模式下构建 C# 解决方案
0
当我发布 Web 应用程序时,AfterPublish 脚本不运行
0
构建时 T4 转换的产品仅在下一个构建中使用
0
ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
0
新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
0
如何将条件编译符号(DefineConstants)传递给 msbuild
0
MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
0
NuGet 包还原找不到包,没有源
0
使用 C# 6.0 功能运行 TFS 构建
0
