我想第一次在c#中创建数据访问层。所以我阅读并使用了教程...现在我有一个简单的代码,但是这段代码不起作用......
for ex:for my delete query ...
这是删除网络方法:
[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);
收到此错误:“附近的语法不正确 关键字'where'。“
我的代码问题是什么?
答案 0 :(得分:0)
您应该使用更像下面的方法 - 您正确使用连接和命令:
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();
}
}
请点击此处了解有关您需要使用的原因的详细信息:[https://www.dotnetperls.com/sqlconnection]
答案 1 :(得分:0)
在删除方法中尝试此代码: -
您可以对连接字符串进行硬编码,而不是从配置文件中读取。 另外,对我来说,桌子是员工,对你而言,它可能是你的桌名。
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();
}
}