62,052
社区成员
发帖
与我相关
我的任务
分享
private static SqlConnection connection;
public static SqlConnection Connection
{
get
{
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
if (connection == null)
{
connection = new SqlConnection(connectionString);
connection.Open();
}
else if (connection.State == System.Data.ConnectionState.Closed)
{
connection.Open();
}
else if (connection.State == System.Data.ConnectionState.Broken)
{
connection.Close();
connection.Open();
}
return connection;
}
}
public DataTable GetDataTable(string commandText)
{
try
{
using (SqlDataAdapter da = new SqlDataAdapter(commandText,Connection))
{
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
catch (Exception ex)
{
string tsql = "";
if (bShowSql)
tsql = commandText;
throw new Exception(tsql + " " + ex.Message);
}
}
public Object ExecuteScalar(string commandText)
{
try
{
using (SqlCommand comm = new SqlCommand(commandText,Connection))
{
return comm.ExecuteScalar();
}
}
catch (Exception ex)
{
string tsql = "";
if (bShowSql)
tsql = commandText;
throw new Exception(tsql + " " + ex.Message);
}
}
using (SqlCommand comm = new SqlCommand(commandText,Connection))
{
object ob = comm.ExecuteScalar();
connection.Close();
return ob;
}