using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace Windowscontrol//工程名
{
class OperateDB//数据库名
{
public static string connectionString = "Server=WIN-41J9I28H5RO;Integrated Security=True;DataBase=certifDB";
SqlConnection conn = new SqlConnection(connectionString);
/// <summary>
/// 返回数据集
/// </summary>
/// <param name="sqlstring"> sql语句</param>
/// <param name="tableName"> 虚拟表的名字</param>
/// <returns>返回dataset对象</returns>
public DataSet GetDataSet(string sqlstring, string tableName)
{
try
{
conn.Open();
SqlCommand mycomm = new SqlCommand(sqlstring, conn);
SqlDataAdapter myda = new SqlDataAdapter(mycomm);
DataSet myds = new DataSet();
myda.Fill(myds, tableName);
return myds;
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
#region open
/// <summary>
/// 打开数据库连接
/// </summary>
private void Open()
{
if (conn == null)
{
conn = new SqlConnection(connectionString);
}
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
}
#endregion
#region close
/// <summary>
/// 关闭连接
/// </summary>
public void close()
{
if (conn != null && conn.State != ConnectionState.Closed)
{
conn.Close();
}
}
#endregion
#region Dispose
/// <summary>
/// 释放数据库连接资源
/// </summary>
public void Dispose()
{
if(conn!=null)
{
conn.Dispose();
conn = null;
}
}
#endregion
#region
/// <summary>
/// 执行SqlCommand命令
/// </summary>
/// <param name="sqlstring">sql语句</param>
/// <returns></returns>
public int ExecuteSql(string sqlstring)
{
this.Open();
SqlCommand com = new SqlCommand(sqlstring, conn);
int n = com.ExecuteNonQuery();
this.close();
return n;
}
#endregion
#region
/// <summary>
/// 创建SqlDataReader对象
/// </summary>
/// <param name="sqlstring">select语句</param>
/// <returns>返回SqlDataReader对象</returns>
public SqlDataReader GetDataReader(string sqlstring)
{
conn.Open();
SqlCommand com = new SqlCommand(sqlstring, conn);
SqlDataReader dr = com.ExecuteReader(CommandBehavior.CloseConnection);
return dr;
}
#endregion
}
}