【问题标题】:Data Access Layer in c#c#中的数据访问层
【发布时间】: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


【解决方案1】:

您应该使用更像下面的方法 - 您正确使用连接和命令:

using (var connection = new SqlConnection((string.Format(_conString, DBname))
{
    using (var command = connection.CreateCommand())
    {
        connection.Open();
        command.CommandText = "delete  from " + tName + " where " + field +  " = " + condition ; 
        command.ExecuteNonQuery();
    }
}

请参阅此处了解为什么需要使用 using 的更多详细信息:[https://www.dotnetperls.com/sqlconnection]

【讨论】:

  • 这是SqlConnection等一次性对象的正确用法但是OP的错误不同。
  • 我先做这个。但它不起作用......我一直在努力......谢谢
【解决方案2】:

在你的删除方法中试试这个代码:-

您可以对连接字符串进行硬编码,而不是从配置文件中读取。 另外,对我来说,表是 Employee,对你来说,它可能是你的表名。

static void Main(string[] args)
    {
        tableName = "Employee";
        string condition = "'User4'";
        Delete("Name", condition);
    }

public static void Delete(string field, string condition)
    {
        string _conString = ConfigurationManager.AppSettings["ConnectionString"];

        using (SqlConnection connect = new SqlConnection(_conString))
        {
            SqlDataAdapter adp = new SqlDataAdapter();

            adp.SelectCommand = new SqlCommand();
            adp.SelectCommand.Connection = connect;

            adp.SelectCommand.CommandText = "delete  from " + tableName + " where " + field + " = " + condition;
            DataSet ds = new DataSet();
            connect.Open();
            adp.Fill(ds);
            connect.Close();
        }
    }

【讨论】:

  • 我知道这项工作。但它不可重复使用。如果我想更改我的目标表,我必须在这里更改表名!但非常感谢:)
  • 您可以先设置tableName属性,然后使用代码...我已经更新了方法请检查它是否适合您。
猜你喜欢
  • 2017-07-08
  • 2011-07-20
  • 1970-01-01
  • 2013-11-27
  • 2011-10-20
  • 2015-07-13
  • 2012-06-21
  • 1970-01-01
相关资源
最近更新 更多