【发布时间】:2017-04-25 05:53:43
【问题描述】:
我想第一次在 c# 中创建一个数据访问层。所以我阅读并使用了教程......现在我有一个简单的代码,但是这个代码不起作用......
例如:对于我的删除查询...
这是删除网络方法:
[WebMethod]
public void DeleteMethod(string DBName, string tableName, string attributes, string values)
{
DBName = DAL.dataAccess.DBname;
tName = DAL.dataAccess.tName;
DAL.dataAccess.Delete(attributes, values);
}
此方法将元素传递给dataAccess 类,该类创建查询并连接到我的数据库。删除查询的dataAccess类代码:
public static string DBname { get;set; }
public static string tableName { get;set; }
public static void Delete(string field, string condition)
{
connect = new SqlConnection(string.Format(_conString, DBname));
adp.SelectCommand = new SqlCommand();
adp.SelectCommand.Connection = connect;
adp.SelectCommand.CommandText = "delete from " + tName + " where " + field + " = " + condition ;
DataSet ds = new DataSet();
connect.Open();
adp.Fill(ds);
connect.Close();
}
起初我使用cmd.ExecuteNonQuery(); 而不是adp.Fill(ds);,但这不起作用并出现错误。所以我把我的代码改成了这个......
现在我在
adp.Fill(ds);收到此错误:“靠近 关键字‘哪里’。”
我的代码有什么问题??
【问题讨论】:
-
你的错误是什么?你应该使用
ExecuteNonQuery();。 -
编辑我的帖子...
-
在 c# 代码中使用内联查询是一种不好的做法,很容易导致 sql 注入。改用存储过程!
-
观察你的查询结果“adp.SelectCommand.CommandText”,你就会知道确切的查询被触发了
-
另外,我认为您在 Web 服务中暴露了太多访问权限。接受表、字段和条件来构建动态查询是不好的。您最好使用存储库。
标签: c# data-access-layer