非常Easy的C#代码去连接访问数据库
这里我们新建一个DBAccess类,并新建一个DBAccess() 的初始化方法
public DBAccess()
{
this.Initialization();
}
private void Initialization()
{
this.m_IsInTransanction = false;
this.m_IsDisposed = false;
this.m_Connection = new SqlConnection(DBConfig.GetConfig(ConfigName));
}
这里的DBConfig是为了获取服务器参数,在你的配置里需要添加
key=”DBConnection”
id=“sa”;
password=“”;
Database=“DateBaseName”
public static string GetConfig(string Name)
{
if (Name == "")
Name = "DBConnection";
string connString = ConfigurationManager.AppSettings["DBConnection"];
if (connString != null)
return connString;
else return "";
}
在DBAccess类中,新建CallSP方法:
commandText 就是你的存储过程名称
SqlParameter[] 这个就是你的参数数组名称
/// <summary>
/// 调用存贮过程,CommandType 在调用时为StoredProcedure,调用结束后改回初始值
/// </summary>
/// <param name="commandText"></param>
/// <param name="commandParameters"></param>
/// <returns></returns>
public DataSet CallSP(string commandText, params SqlParameter[] commandParameters)
{
System.Data.CommandType oldCommandType = CommandType;
try
{
this.CommandType = System.Data.CommandType.StoredProcedure;
return this.GetDataSet(commandText, commandParameters);
}
finally
{
this.CommandType = oldCommandType;
}
}
/// <summary>
/// 得到 DataSet
/// </summary>
/// <param name="commandText"></param>
/// <param name="commandParameters"></param>
/// <returns></returns>
public DataSet GetDataSet(string commandText, params SqlParameter[] commandParameters)
{
SqlCommand command1 = new SqlCommand(commandText, this.m_Connection);
command1.CommandTimeout = 3000;
command1.CommandType = CommandType;
DataSet set1 = new DataSet();
FillDataSet(commandText, set1, commandParameters);
return set1;
}
/// <summary>
/// Fill DataSet
/// </summary>
/// <param name="commandText">Command string</param>
/// <param name="theDataSet">Refere to DataSe</param>
/// <param name="commandParameters">Array for Parameters</param>
public void FillDataSet(string commandText, DataSet theDataSet, params SqlParameter[] commandParameters)
{
SqlCommand command1 = new SqlCommand(commandText, this.m_Connection);
command1.CommandType = CommandType;
if (this.m_IsInTransanction)
{
command1.Transaction = this.m_Transanction;
}
if (commandParameters != null)
{
DBAccess.AttachParameters(command1, commandParameters);
}
try
{
SqlDataAdapter adapter1 = new SqlDataAdapter(command1);
adapter1.Fill(theDataSet);
}
catch (Exception err)
{
}
finally
{
if (!this.m_IsInTransanction)
{
this.Close();
}
}
}
private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
{
SqlParameter[] parameterArray1 = commandParameters;
for (int num1 = 0; num1 < parameterArray1.Length; num1++)
{
SqlParameter parameter1 = parameterArray1[num1];
if (parameter1 != null)
{
command.Parameters.Add(parameter1);
}
}
}
最后关闭连接
public void Close()
{
if (this.m_Connection != null)
{
this.m_Connection.Close();
}
}
调用存储过程需要在WebConfig 的appSettings里面添加KEY,并保证数据库能正常运行;
祝你们好运!