1

我正在使用此代码删除表中的一行,但它不起作用。我会犯错还是错过了什么?

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

4

2 回答 2

1

旁观者和伙计们。
谢谢你的帮助。
经过多次尝试,我找到了解决方案。

BookID 是列名,这个符号 必须在列名前后加上。

因此正确的做法是:

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

这是错误的:

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


再次感谢您的帮助。

于 2010-11-26T06:25:20.127 回答
0

您是否尝试过使用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(); 
}
于 2010-11-26T04:44:39.303 回答