欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#使用SqlConnection连接到SQL Server的代码示例

程序员文章站 2023-11-19 08:21:16
使用sqlconnection连接到sql server 2012 示例如下: (1). 利用sqlconnection创建连接 public sqlserv...

使用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创建连接代码示例详解整合,希望对大家有所帮助