使用不同的命令多次使用 sql 命令

发布于 2024-10-27 15:58:34 字数 1284 浏览 1 评论 0原文

我一直在尝试使用相同的 SqlConnectionSqlCommand 对象来执行不同的命令。

第一个检查是否重复,第二个如果用户输入的数据不重复则插入数据。

这是我的代码示例:

        using (SqlConnection conn = new SqlConnection(ConnStr))
        {
            string Command = "SELECT CountryName FROM [Countries] WHERE CountryName = @Name";

            using (SqlCommand comm = new SqlCommand(Command, conn))
            {
                comm.Parameters.Add("@Name", System.Data.SqlDbType.NVarChar, 20);
                comm.Parameters["@Name"].Value = Name;

                comm.Parameters.Add("@IsVisible", System.Data.SqlDbType.Bit);
                comm.Parameters["@IsVisible"].Value = IsVisible;

                conn.Open();

                if (comm.ExecuteScalar() == null)
                {
                        Command = "INSERT INTO [Countries] (CountryName, IsVisible) VALUES (@Name, @IsVisible);";
                        comm.ExecuteNonQuery();
                }
        }

我试图通过使用一个连接来保存对数据库的访问。

问题是:

第一个命令运行正常,但是 第二个命令插入 数据库将无法工作(它不会添加 数据库的任何记录),当我 试图显示影响它的行 给了我-1!!

问题是:

这是检查的理想方法吗? a 重复记录来约束 a 独特的国家?以及为什么第二个 命令未执行?

I've been trying to use the same SqlConnection and SqlCommand objects to execute to different commands.

the first one checks for duplicate and the second one inserts the data if the data the user entered is not a duplicate.

Here's a sample of my code:

        using (SqlConnection conn = new SqlConnection(ConnStr))
        {
            string Command = "SELECT CountryName FROM [Countries] WHERE CountryName = @Name";

            using (SqlCommand comm = new SqlCommand(Command, conn))
            {
                comm.Parameters.Add("@Name", System.Data.SqlDbType.NVarChar, 20);
                comm.Parameters["@Name"].Value = Name;

                comm.Parameters.Add("@IsVisible", System.Data.SqlDbType.Bit);
                comm.Parameters["@IsVisible"].Value = IsVisible;

                conn.Open();

                if (comm.ExecuteScalar() == null)
                {
                        Command = "INSERT INTO [Countries] (CountryName, IsVisible) VALUES (@Name, @IsVisible);";
                        comm.ExecuteNonQuery();
                }
        }

I was trying to save a trip to the database by using one connection.

The Problem is:

The first command runs okay but the
second command which inserts into the
database won't work (it doesn't add
any records to the db) and when I
tried to display the rows affected it
gave me -1 !!

The Question is:

Is this is the ideal way to check for
a duplicate records to constraint a
unique country ? and why the second
command is not executing ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

总以为 2024-11-03 15:58:34

您正在更改 string Command 的值,但实际上从未更改 SqlCommand comm 中的命令字符串。

You are changing the value of string Command, but you are never actually changing the command string in SqlCommand comm.

芸娘子的小脾气 2024-11-03 15:58:34

当您使用 insert 语句重写 Command 变量时,您只是修改了之前定义的名为 Command 的字符串。您没有修改存储在 SqlCommand 对象内的命令文本。

尝试:

comm.CommandText = "INSERT INTO [Countries] (CountryName, IsVisible) VALUES (@Name, @IsVisible);";

When you rewrite the Command variable with the insert statement, you are simply modifying the string named Command that you've defined earlier. You are not modifying the command text stored inside of the SqlCommand object.

Try:

comm.CommandText = "INSERT INTO [Countries] (CountryName, IsVisible) VALUES (@Name, @IsVisible);";

南七夏 2024-11-03 15:58:34

回答你的第一个问题:不,这不是确保国家/地区名称唯一性的方法。在您的数据库中,您应该定义您的 Country 表,以便 CountryName 成为主键(或者,您可以将其他列声明为 PK 并在 CountryName 上定义唯一约束)。

然后,尝试插入重复值将引发异常,您可以适当处理该异常(丢弃现有记录、覆盖它、提示用户输入不同的值等)。

通过您的方法检查唯一性被认为是不好的,因为 A) 它将属于数据库本身的逻辑放入应用程序的代码中; B) 它引入了潜在的竞争条件,其中某些其他应用程序或线程在您读取数据库和写入数据库之间插入一个值。

To answer your first question: no, this is not the way to ensure uniqueness for country name. In your database, you should define your Countries table so that CountryName is the primary key (alternatively, you can declare some other column as the PK and define a unique constraint on CountryName).

The attempt to insert a duplicate value, then, will throw an exception, which you can handle appropriately (discard the existing record, overwrite it, prompt the user for a different value etc.).

Checking for uniqueness via your method is considered bad because A) it places logic that belongs in the database itself into your application's code; and B) it introduces a potential race condition, wherein some other application or thread inserts a value in between your read of the database and your write to it.

羁〃客ぐ 2024-11-03 15:58:34

我建议将插入与选择语句分开。
比如:

    private void Insert()
    {
        using (SqlConnection conn = new SqlConnection(ConnStr)) 
         {             
        string Command = "INSERT INTO [Countries] (CountryName, IsVisible) VALUES (@Name, @IsVisible)";    

        using (SqlCommand comm = new SqlCommand(Command, conn)) 
         {
        comm.Parameters.Add("@Name", System.Data.SqlDbType.NVarChar, 20); 
        comm.Parameters["@Name"].Value = Name;
        comm.Parameters.Add("@IsVisible", System.Data.SqlDbType.Bit);                 comm.Parameters["@IsVisible"].Value = IsVisible;
        conn.Open(); 

        comm.ExecuteNonQuery();

        conn.Close();
        } 

}

private void SelectInsert()
{
      using (SqlConnection conn = new SqlConnection(ConnStr)) 
     {             
    string Command = "SELECT CountryName FROM [Countries] WHERE CountryName = @Name";              
    using (SqlCommand comm = new SqlCommand(Command, conn)) 
     {
    comm.Parameters.Add("@Name", System.Data.SqlDbType.NVarChar, 20); 
    comm.Parameters["@Name"].Value = Name;

    conn.Open(); 
    if (comm.ExecuteScalar() == null)
    { 

           Insert(); //your save method

     }
    } 
}

问候

I thing i suggest to seperate the insert with your select statement..
someting like:

    private void Insert()
    {
        using (SqlConnection conn = new SqlConnection(ConnStr)) 
         {             
        string Command = "INSERT INTO [Countries] (CountryName, IsVisible) VALUES (@Name, @IsVisible)";    

        using (SqlCommand comm = new SqlCommand(Command, conn)) 
         {
        comm.Parameters.Add("@Name", System.Data.SqlDbType.NVarChar, 20); 
        comm.Parameters["@Name"].Value = Name;
        comm.Parameters.Add("@IsVisible", System.Data.SqlDbType.Bit);                 comm.Parameters["@IsVisible"].Value = IsVisible;
        conn.Open(); 

        comm.ExecuteNonQuery();

        conn.Close();
        } 

}

private void SelectInsert()
{
      using (SqlConnection conn = new SqlConnection(ConnStr)) 
     {             
    string Command = "SELECT CountryName FROM [Countries] WHERE CountryName = @Name";              
    using (SqlCommand comm = new SqlCommand(Command, conn)) 
     {
    comm.Parameters.Add("@Name", System.Data.SqlDbType.NVarChar, 20); 
    comm.Parameters["@Name"].Value = Name;

    conn.Open(); 
    if (comm.ExecuteScalar() == null)
    { 

           Insert(); //your save method

     }
    } 
}

Regards

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文