阻止用户在数据库c中两次输入相同的数字#

时间:2014-02-20 02:33:19

标签: c# winforms ms-access datagridview

我已经创建了windows表单,该函数用于将信息添加到数据库中。但是,我有一个问题。当我在“产品代码”列中输入类似“SM0001”的数字,然后按回车键,它将数据存储到数据库中,当我输入与之前输入的相同的数字时,它不会阻止用户像输入“产品代码”已存在于数据库中。所以,这是我当前的数据库(显示在系统的datagridview中):

enter image description here

如您所见,行“1”和行“2”具有相同的“产品代码”..我的问题是:如何阻止用户输入相同的数字两次?

以下是我用来存储到数据库的代码:

private void AddDatabase(object sender, EventArgs e)
        {
            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                string query = "INSERT INTO [Record] ([ProductCode], [Quantity], [Description], [SubTotal], [Total], [IssuedBy], [To], [Dates], [Times]) VALUES (@ProductCode, @Quantity, @Description, @SubTotal, @Total, @IssuedBy, @To, @Dates, @Times)";
                string _query = "INSERT INTO [TransRecord] ([ProductCode], [Quantity], [Description], [SubTotal], [Total], [IssuedBy], [To], [Dates], [Times]) VALUES (@ProductCode, @Quantity, @Description, @SubTotal, @Total, @IssuedBy, @To, @Dates, @Times)";

                conn.Open();

                using (OleDbCommand cmd = new OleDbCommand(query, conn))
                {
                    cmd.Parameters.Add("@ProductCode", System.Data.OleDb.OleDbType.VarChar);
                    cmd.Parameters["@ProductCode"].Value = this.numericTextBox1.Text;

                    cmd.Parameters.Add("@Quantity", System.Data.OleDb.OleDbType.Integer);
                    cmd.Parameters["@Quantity"].Value = Convert.ToInt32(this.numericUpDown1.Value);

                    cmd.Parameters.Add("@Description", System.Data.OleDb.OleDbType.VarChar);
                    cmd.Parameters["@Description"].Value = this.textBox5.Text;

                    cmd.Parameters.Add("@SubTotal", System.Data.OleDb.OleDbType.Integer);
                    cmd.Parameters["@SubTotal"].Value = Convert.ToInt32(this.numericTextBox2.Text);

                    cmd.Parameters.Add("@Total", System.Data.OleDb.OleDbType.Integer);
                    cmd.Parameters["@Total"].Value = Convert.ToInt32(this.numericTextBox3.Text);

                    cmd.Parameters.Add("@IssuedBy", System.Data.OleDb.OleDbType.VarChar);
                    cmd.Parameters["@IssuedBy"].Value = this.textBox1.Text;

                    cmd.Parameters.Add("@To", System.Data.OleDb.OleDbType.VarChar);
                    cmd.Parameters["@To"].Value = this.textBox2.Text;

                    cmd.Parameters.Add("@Dates", System.Data.OleDb.OleDbType.Date);
                    cmd.Parameters["@Dates"].Value = this.textBox3.Text;

                    cmd.Parameters.Add("@Times", System.Data.OleDb.OleDbType.DBTimeStamp);
                    cmd.Parameters["@Times"].Value = DateTime.Now.ToShortTimeString();

                    cmd.ExecuteNonQuery();

                    using (OleDbCommand _cmd = new OleDbCommand(_query, conn))
                    {
                        _cmd.Parameters.Add("@ProductCode", System.Data.OleDb.OleDbType.VarChar);
                        _cmd.Parameters["@ProductCode"].Value = this.numericTextBox1.Text;

                        _cmd.Parameters.Add("@Quantity", System.Data.OleDb.OleDbType.Integer);
                        _cmd.Parameters["@Quantity"].Value = Convert.ToInt32(this.numericUpDown1.Value);

                        _cmd.Parameters.Add("@Description", System.Data.OleDb.OleDbType.VarChar);
                        _cmd.Parameters["@Description"].Value = this.textBox5.Text;

                        _cmd.Parameters.Add("@SubTotal", System.Data.OleDb.OleDbType.Integer);
                        _cmd.Parameters["@SubTotal"].Value = Convert.ToInt32(this.numericTextBox2.Text);

                        _cmd.Parameters.Add("@Total", System.Data.OleDb.OleDbType.Integer);
                        _cmd.Parameters["@Total"].Value = Convert.ToInt32(this.numericTextBox3.Text);

                        _cmd.Parameters.Add("@IssuedBy", System.Data.OleDb.OleDbType.VarChar);
                        _cmd.Parameters["@IssuedBy"].Value = this.textBox1.Text;

                        _cmd.Parameters.Add("@To", System.Data.OleDb.OleDbType.VarChar);
                        _cmd.Parameters["@To"].Value = this.textBox2.Text;

                        _cmd.Parameters.Add("@Dates", System.Data.OleDb.OleDbType.Date);
                        _cmd.Parameters["@Dates"].Value = this.textBox3.Text;

                        _cmd.Parameters.Add("@Times", System.Data.OleDb.OleDbType.DBTimeStamp);
                        _cmd.Parameters["@Times"].Value = DateTime.Now.ToShortTimeString();

                        _cmd.ExecuteNonQuery();
                    }

                    if (_choice.comboBox1.Text == "English")
                    {
                        System.Media.SoundPlayer _sound = new System.Media.SoundPlayer(@"C:\Windows\Media\Windows Exclamation.wav");
                        _sound.Play();

                        DialogResult _dialogResult = MessageBox.Show("Added Successfully!", "Success", MessageBoxButtons.OK);

                        if (_dialogResult == DialogResult.OK)
                        {
                            ViewDatabase(sender, e);

                            ClearTextBox(sender, e);
                        }
                    }

                    dataGridView1.ClearSelection();
                }

                conn.Close();
            }
        }

3 个答案:

答案 0 :(得分:2)

使用SQL Server EXISTS语法。

IF NOT EXISTS (SELECT * FROM Recrd WHERE (PRoductCode  = @ProductCode))
BEGIN
    INSERT INTO [Record] ([ProductCode], [Quantity], [Description], [SubTotal], [Total], [IssuedBy], [To], [Dates], [Times]) VALUES (@ProductCode, @Quantity, @Description, @SubTotal, @Total, @IssuedBy, @To, @Dates, @Times)


    END
    ELSE
    BEGIN
do an update or give me some message
    END

好的,对于Access。我不是很好,但我认为这样的事情会起作用:

int intNumRows; 
string query = "SELECT COUNT(*) FROM [Record ] WHERE PRoductCode = @ProductCode "; 
objCmd = new OleDbCommand(strSQL, objConn); 
intNumRows = Convert.ToInt32(objCmd.ExecuteScalar()); 
if(intNumRows > 0) 
{ 
this.lblStatus.Text = "Record already exists for this customer."; 
} 
else
{ 
 string query = "INSERT INTO [Record] ([ProductCode], [Quantity], [Description], [SubTotal], [Total], [IssuedBy], [To], [Dates], [Times]) VALUES (@ProductCode, @Quantity, @Description, @SubTotal, @Total, @IssuedBy, @To, @Dates, @Times)";
                string _query = "INSERT INTO [TransRecord] ([ProductCode], [Quantity], [Description], [SubTotal], [Total], [IssuedBy], [To], [Dates], [Times]) VALUES (@ProductCode, @Quantity, @Description, @SubTotal, @Total, @IssuedBy, @To, @Dates, @Times)";

---
---

答案 1 :(得分:1)

根据底层数据库,使用unique = true

在所需列上创建索引

答案 2 :(得分:1)

您可以将列设为主要列或唯一列,然后当您尝试插入时,您将获得异常。

如果您无法更改数据库,则可以在插入之前检查ProductCode是否存在

Select count(*) from [Record] where ProductCode =@ProductCode

设置参数并运行cmd.ExcuteScaler(),根据返回值,您可以显示消息,如"Product Code" already exists或插入

conn.Open();
using (OleDbCommand cmd = new OleDbCommand("Select count(*) from  [Record] where ProductCode =@ProductCode", conn))
{
   cmd.Parameters.AddWithValue("@ProductCode",this.numericTextBox1.Text);
   object count = command.ExecuteScalar();
   int intcount;
   if(count !=null && int.TryParse(count.Tostring(), out intcount) && intcount >0)
   {
     // Product Code already exists, you can show error message to user 
     return;
   }
}

// your code ..
string query = "INSERT INTO [Record] ([ProductCode], [Quantity], [Description], [SubTotal], [Total], [IssuedBy], [To], [Dates], [Times]) VALUES (@ProductCode, @Quantity, @Description, @SubTotal, @Total, @IssuedBy, @To, @Dates, @Times)";
string _query = "INSERT INTO [TransRecord] ([ProductCode], [Quantity], [Description], [SubTotal], [Total], [IssuedBy], [To], [Dates], [Times]) VALUES (@ProductCode, @Quantity, @Description, @SubTotal, @Total, @IssuedBy, @To, @Dates, @Times)";

using (OleDbCommand cmd = new OleDbCommand(query, conn))