【发布时间】:2018-07-06 10:12:50
【问题描述】:
我正在使用 3 层架构来构建网站。为此,我创建了一个名为 DB Manager 的类。
这是课程
namespace DAL
{
class DBManager
{
private static DataTable dt = new DataTable();
private static string ConnectionString = System.Configuration.ConfigurationManager.AppSettings["SQLSERVER"];
public static int ExecuteNonQuery(string query)
{
int result;
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand(query, con);
try
{
con.Open();
result = command.ExecuteNonQuery();
con.Close();
}
catch
{
result = -1;
}
finally
{
con.Close();
}
return result;
}
public static DataTable ExecuteDataTable(string query)
{
SqlConnection con = new SqlConnection(ConnectionString);
SqlDataAdapter da = new SqlDataAdapter();
dt = new DataTable();
try
{
con.Open();
da.SelectCommand = new SqlCommand(query, con);
con.Close();
da.Fill(dt);
}
catch
{
dt.Rows.Clear();
}
return dt;
}
public static string ExecuteScaler(string query)
{
SqlConnection con = new SqlConnection(ConnectionString);
SqlDataAdapter da = new SqlDataAdapter();
string result = string.Empty;
try
{
con.Open();
da.SelectCommand = new SqlCommand(query, con);
con.Close();
dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count == 1 && dt.Columns.Count == 1)
{
result = dt.Rows[0][0].ToString();
}
}
catch
{
result = string.Empty;
}
return result;
}
public static bool ExecuteReader(string query)
{
bool result = false;
SqlConnection con = new SqlConnection(ConnectionString);
SqlDataAdapter da = new SqlDataAdapter();
try
{
con.Open();
da.SelectCommand = new SqlCommand(query, con);
con.Close();
dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count == 1 && dt.Columns.Count == 1)
{
if (dt.Rows[0][0].ToString() == "true")
{
result = true;
}
else
{
result = false;
}
}
} catch (Exception)
{
result = false;
}
return result;
}
}
}
当我这样查询时
query = "insert into client(account_id, name, receive_email) values(" + accountId + ", '" + clientBLL.name + "', " + clientBLL.receiveMail + ");";
但是这种查询方法应该是非常糟糕的主意。好的方法是向 SqlCommand 中提供要插入或检索哪些数据的参数。
这样
query = @"insert into accounts(email, password, user_type) output inserted.id values(@email, @password, @userType);";
cmd.Parameters.Add("email", SqlDbType.NVarChar).Value = bll.email;
cmd.Parameters.Add("password", SqlDbType.VarBinary).Value = bll.password;
cmd.Parameters.Add("userType", SqlDbType.Bit).Value = 0;
但是我的 DB Manager 类不支持这种方法。我想要一个支持这种 Sql 命令查询方法的 Db Manager 类,而不是旧的(我之前表达过的)。我该怎么做。
【问题讨论】:
-
天哪! 我该怎么做...显然您需要将参数添加到您的数据库管理器。我有一门完整的课程,可以传给你。但老实说,你为什么不使用现成的东西呢?检查Dapper,这是一个非常酷的库。
-
是的!但我不想使用图书馆请你给我上课吗?
标签: c# asp.net data-access-layer 3-tier