简体   繁体   English

删除SQL行并更改ID

[英]Delete SQL row and change Id

I am making a C# tool that connects to a SQL database to manage users for another program I created. 我正在制作一个连接到SQL数据库的C#工具,以管理我创建的另一个程序的用户。 I'm displaying the Users in a ListBox , and I can add/delete users. 我在ListBox显示用户,并且可以添加/删除用户。 Things got weird after I deleted some profiles, and I thought that could have something to do with how I delete the row from the database. 删除一些概要文件后,事情变得很奇怪,我认为这可能与我从数据库中删除行有关。 I'm using an Id that automatically increases with every new user creation. 我使用的ID在每次创建新用户时都会自动增加。 This is my code for deleting from the database: 这是我从数据库中删除的代码:

using (conn = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand("DELETE FROM myDatabase WHERE Id = '" + (listBox1.SelectedIndex + 1) + "'", conn))
{
    conn.Open();
    command.ExecuteNonQuery();
}

and this is how I load the users into my listbox: 这就是我将用户加载到列表框中的方式:

using (conn = new SqlConnection(connectionString))
using (SqlDataAdapter sqlAdapt = new SqlDataAdapter("SELECT * FROM myDatabase", conn))
{
    DataTable dataTable = new DataTable();
    sqlAdapt.Fill(dataTable);
    listBox1.DisplayMember = "Name";
    listBox1.ValueMember = "Id";
    listBox1.DataSource = dataTable;
}

How can I delete the correct row from the database? 如何从数据库中删除正确的行?

You should use the property SelectedValue to find your ID not the SelectedIndex 您应该使用属性SelectedValue查找您的ID,而不是SelectedIndex

if(listBox1.SelectedValue != null)
{
    int userID = Convert.ToInt32(listBox1.SelectedValue);
    using (conn = new SqlConnection(connectionString))
    using (SqlCommand command = new SqlCommand("DELETE FROM myDatabase WHERE Id = @uid", conn))
    {

        conn.Open();
        command.Parameters.Add("@uid", MySqlDbType.Int32).Value = userID;
        command.ExecuteNonQuery();
    }
}

The problem with SelectedIndex is that this value goes from 0 to the max number of items in the listbox. SelectedIndex的问题在于此值从0到列表框中的最大项目数。 This value has nothing to do with the ID of your user automatically calculated by your database. 此值与数据库自动计算出的用户标识无关。 (After just one delete and one add these value are out of synch) (仅一次删除和一次添加后,这些值不同步)

Note also that an sql text should never built using string concatenation. 还要注意,永远不要使用字符串连接构建sql文本。 This is a well know security problem called Sql Injection . 这是一个众所周知的安全问题,称为Sql Injection

"DELETE FROM myDatabase WHERE Id = '" + (listBox1.SelectedIndex + 1) + "'"

I'm not sure about mySQL, but it looks like you pass a string instead of an int. 我不确定mySQL,但看起来您传递的是字符串而不是int。 When you pass a parameter as a number you should remove the " ' ". 当您将参数作为数字传递时,应删除“”。 so, it will look like: 因此,它将看起来像:

"DELETE FROM myDatabase WHERE Id = " + (listBox1.SelectedValue)

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

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