sql更新查询不更新表数据

jhdbpxl9  于 2021-08-13  发布在  Java
关注(0)|答案(3)|浏览(511)

这是我的代码,它显示成功,但不更新表中的行。

cm = new SqlCommand("update table_products set pname = @pname, pdesc = @pdesc, bid = @bid, cid = @cid, cost = @cost, price = @price, reorder = @reorder where pcode like @pcode", con);

cm.Parameters.AddWithValue("@pcode", tft_pcode.Text);
cm.Parameters.AddWithValue("@barcode", tft_barcode.Text);
cm.Parameters.AddWithValue("@pname", tft_pname.Text);
cm.Parameters.AddWithValue("@pdesc", tft_pdescription.Text);
cm.Parameters.AddWithValue("@bid", bid);
cm.Parameters.AddWithValue("@cid", cid);
cm.Parameters.AddWithValue("@cost", Double.Parse(tft_cost.Text));
cm.Parameters.AddWithValue("@price", Double.Parse(tft_price.Text));
cm.Parameters.AddWithValue("@reorder", int.Parse(tft_reorder.Text));

cm.ExecuteNonQuery();
con.Close();

MessageBox.Show("Product updated successfully");
w51jfk4q

w51jfk4q1#

cm.ExecuteNonQuery(); 返回受影响的行数。在您的例子中,它可能是0(但仍然值得获取值并检查)。
对你来说,听起来 where pcode like @pcode 在查询结束时,不匹配表中的任何内容。

var rowsUpdated = cm.ExecuteNonQuery();
con.Close();

if(rowsUpdate>0) MessageBox.Show("Product updated successfully");
else MessageBox.Show("Product NOT updated successfully");
frebpwbc

frebpwbc2#

如果您使用的是基于文件的数据库,例如在运行项目时动态附加到db服务器的sqlservermdf文件,那么您应该知道,您的程序正在更新的db不一定与您在managementstudio中查找的文件相同。看看你的连接字符串——如果它提到datadirectory,那么很可能是bin/debug或bin/release(取决于你的活动构建配置)文件夹中的数据库文件正在更新,而不是项目文件夹中的那个。每次运行项目时,项目文件夹中的数据库都会被复制到bin/*中。这通常是一个可怕的原因“我的程序说它更新了我的数据库,但它没有”-要么数据库被替换为一个干净的一个每次运行的程序,或者开发人员正在寻找一个数据库文件,程序正在更新另一个

e5njpo68

e5njpo683#

我解决了这个问题,问题是我试图将pcode(应用程序)与pcode(数据库)进行匹配,但没有这样做。这是因为当我的更新表单加载时,我在它的事件中有pcode generate方法,所以我在匹配旧的pcode值,它实际上在做的是,它在匹配新生成的pcode。所以我从表单加载事件中删除了pcodegenerate方法,问题就解决了。谢谢大家抽出时间。

相关问题