简体   繁体   English

信息反复记录在数据库中

[英]Info repeatedly getting recorded in DB

在此处输入图片说明 I have a Form where I am inserting a record into the database. 我有一个将记录插入数据库的表单。 There are two tables, table_1 is called members , and table_2 is called Amount . 有两个表,table_1称为members ,table_2称为Amount

I am using two SQL INSERT statements to send records to database , because that's the way I have figured out -- there might be other ways, which I don't know. 我正在使用两个SQL INSERT语句将记录发送到数据库,因为这是我已经弄清楚的方式-可能还有其他方式,我不知道。

When I insert the record I get a message that it is inserted successfully, but when I check the database the inserted record replaces the one present , so I have last record in the DB repeated several times. 当我插入记录时,我收到一条消息,提示它已成功插入,但是当我检查数据库时,插入的记录将替换当前的记录,因此数据库中的最后一条记录重复了几次。 Please assist. 请协助。

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

namespace CemiyetAidatSistem
{
    public partial class AddMember : Form
    {
        public AddMember()
        {
            InitializeComponent();
        }
        SqlConnection con = new SqlConnection("Data Source=My-PC\\SQLSERVER;Initial Catalog=FredericiaDernek;Integrated Security=True");

        private void btnInsert_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand();
            string Sql = "INSERT INTO Uyeleri ( dID, FullName, Address, Mobile, Email, Comments ) VALUES ('" + txtdID.Text + "', '" + txtAdiSoyadi.Text + "','" + txtAddress.Text + "','" + txtMobile.Text + "','" + txtEmail.Text + "','" + txtComments.Text + "')";
            cmd.CommandText = Sql;
            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();

            Sql = "INSERT INTO Aidat (dID Year, Amount ) VALUES ('"+ txtdID.Text +"','" + txtYear.Text + "','" + txtAmount.Text + "')";
            cmd.CommandText = Sql;
            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();

            for (int i = 0; i < this.Controls.Count; i++)
            {
                if (this.Controls[i] is TextBox)
                {
                    this.Controls[i].Text = "";
                }
            }
            MessageBox.Show("Data Added Scuessfully");
        }

    }
}

I have rewritten your code to correct errors and bad practices 我已经重写了您的代码,以纠正错误和不良做法

string connString = "Data Source=My-PC\\SQLSERVER;Initial Catalog=FredericiaDernek;Integrated Security=True";

private void btnInsert_Click(object sender, EventArgs e)
{
    using(SqlConnection con = new SqlConnection(connString))
    {
        con.Open();
        string Sql = "INSERT INTO Uyeleri (dID, FullName, Address, Mobile, Email, Comments ) " + 
                     "VALUES (@id, @name, @address, @mobile, @email, @comments");
        using(SqlCommand cmd = new SqlCommand(Sql, con))
        {
            cmd.Parameters.AddWithValue("@id", txtdID.Text);
            cmd.Parameters.AddWithValue("@name", txtAdiSoyadi.Text);
            cmd.Parameters.AddWithValue("@address", txtAddress.Text);
            cmd.Parameters.AddWithValue("@mobile", txtMobile.Text);
            cmd.Parameters.AddWithValue("@email", txtEmail.Text);
            cmd.Parameters.AddWithValue("@comments", txtComments.Text);
            cmd.ExecuteNonQuery();

            Sql = "INSERT INTO Aidat (dID, [Year], Amount ) VALUES " + 
                  "(@id, @year, @amount)";
            cmd.Parameters.Clear();
            cmd.CommandText = Sql;  // <- missing this in the previous version.....
            cmd.Parameters.AddWithValue("@id", txtdID.Text);
            cmd.Parameters.AddWithValue("@name", txtYear.Text);
            cmd.Parameters.AddWithValue("@amount", txtAmount.Text);
            cmd.ExecuteNonQuery();
        }
    }

What I have changed: 我改变了什么:

  • The second insert statement is wrong. 第二个插入语句是错误的。 Missing a comma between first and second column 第一列和第二列之间缺少逗号
  • Removed the creation of the SqlConnection at the global level 在全局级别删除了SqlConnection的创建
  • Added appropriate using statement to dispose the SqlConnection and SqlCommand also in case of exceptions 在出现异常的情况下,添加了适当的using语句来处理SqlConnection和SqlCommand
  • Used parameters for the two insert statements 两个插入语句的已用参数
  • Added square brackets around Year field (Year is a reserved keyword in T-SQL) 在“年份”字段周围添加了方括号(“年份”是T-SQL中的保留关键字)

Creating a SqlConnection at the global level is bad, because you grab system resources and you don't dispose them for the lifetime of your application. 在全局级别创建SqlConnection是不好的,因为您会获取系统资源,并且不会在应用程序的生存期内对其进行处理。 And the situation could be out of control in case of exceptions not correctly handled. 如果异常处理不当,情况可能会失控。

Now I have some doubt about your tables. 现在我对您的桌子有些怀疑。 The fields dID (both tables) and Amount are of text type (varchar,nvarchar)?. 字段dID(两个表)和金额都是文本类型(varchar,nvarchar)? If they are of numeric type it is necessary to add a conversion before adding the values to the Parameters collection 如果它们是数字类型,则必须先添加转换,然后再将值添加到Parameters集合中

I would also suggest changing your for loop to clear the controls replace this 我也建议更改您的for循环以清除控件,以取代此

for (int i = 0; i < this.Controls.Count; i++)
{
    if (this.Controls[i] is TextBox)
    {
        this.Controls[i].Text = "";
    }
}

with the following code using linq. 使用linq使用以下代码。

this.Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());

keep in mind that 'this' will refer to the name of your Form 请记住, “ this”将指您表格的名称

so it would be 所以会是

(YourWinFormsName).Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());

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

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