DBHelper

时间:2023-03-10 02:54:45
DBHelper

DBHelper:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data; namespace DAL
{
public class DBhelper
{
private static string Constr = "server=.;database=PaiPaiDB;uid=sa;pwd=123";
private static SqlConnection conn;
private static SqlDataAdapter da;
private static SqlCommand cmd;
private static DBhelper dbhelper; public DBhelper()
{
conn = new SqlConnection(Constr);
} public static DBhelper Instance()
{
if (dbhelper == null)
{
dbhelper = new DBhelper();
}
return dbhelper;
} void DBOpen()
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
} void DBClose()
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
} public DataTable GetDtatTableBySql(string sql)
{
DBOpen(); DataTable dt = new DataTable();
da = new SqlDataAdapter(sql, conn);
try
{
da.Fill(dt);
return dt;
}
catch (Exception)
{ return null;
}
finally
{
DBClose();
}
} public bool ExcuteSql(string sql)
{ DBOpen();
cmd = new SqlCommand(sql, conn);
try
{
cmd.ExecuteNonQuery();
return true;
}
catch (Exception)
{
return false;
}
finally
{
DBClose();
}
} public bool ExcuteProcedure(string proName, SqlParameter[] paras)
{
DBOpen();
cmd = new SqlCommand(proName, conn);
cmd.CommandType = CommandType.StoredProcedure;
for (int i = ; i < paras.Length; i++)
{
cmd.Parameters.Add(paras[i]);
}
try
{
cmd.ExecuteNonQuery();
return true;
}
catch (Exception)
{
return false;
}
finally
{
DBClose();
}
}
}
}

调用方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data; namespace DAL
{
public class GoodsService
{
//查询
public static DataTable GetDtatTableBySql(string sql)
{ DataTable dt = DBhelper.Instance().GetDtatTableBySql(sql);
if (dt != null && dt.Rows.Count > )
{
return dt;
}
else
{
return null;
}
}
//增加 删除 修改
public static bool ExecuteSql(string sql)
{
bool a;
a = DBhelper.Instance().ExcuteSql(sql);
return a;
} }
}