繁体   English   中英

如何在Npgsql中删除表中的行?

[英]How to delete a row in a Table in Npgsql?

我正在使用此代码删除表中的行,但无法正常工作。 我会犯错还是错过了什么?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Npgsql;

namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button_RemoveBook_Click(object sender, EventArgs e)
        {
            NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;User Id=user;Password=1234;Database=library;");
            conn.Open();
            string sql = "DELETE FROM books WHERE BookID=1;";
            NpgsqlCommand command = new NpgsqlCommand(sql, conn);
            conn.Close();
        }
    }
}

运行上面的任务后,我注意到数据库没有进行任何更改。 bookID = 1,即数据库中的第一行。

我试图使用INSERT命令,它可以工作。 新数据已插入到表的最后一行。 下面的代码运行良好。

private void button_addBook_Click(object sender, EventArgs e)
{
    NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;User Id=user;Password=1234;Database=library;");
    conn.Open();
    string addRow = string.Format("insert into books values(50,'Time','Frank','Science')");
    NpgsqlCommand command = new NpgsqlCommand(addRow, conn);
    conn.Close();

有什么线索吗? 谢谢。


回应:旁观者

它显示此错误消息:
http://i901.photobucket.com/albums/ac218/pcser/error.jpg

旁观者和大家。
感谢您的帮助。
经过几次尝试,我找到了解决方案。

BookID是一列的名称,必须在该列名称的前后添加 符号。

因此正确的方法是:

    string sql = "DELETE FROM books WHERE \"BookID\"=1;"; 

这是错误的:

    string sql = "DELETE FROM books WHERE BookID=1;"; 


再次感谢你的帮助。

您是否尝试过使用NpgsqlCommand.ExecuteNonQuery方法

就像是

private void button_RemoveBook_Click(object sender, EventArgs e) 
{ 
    NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;User Id=user;Password=1234;Database=library;"); 
    conn.Open(); 
    string sql = "DELETE FROM books WHERE BookID=1;"; 
    NpgsqlCommand command = new NpgsqlCommand(sql, conn); 
    command.ExecuteNonQuery(); //this line here??
    conn.Close(); 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM