C# 如果不存在,则插入else show消息;“已经存在”;

C# 如果不存在,则插入else show消息;“已经存在”;,c#,sql-server,C#,Sql Server,我是C#编码新手,所以我试着像下面代码中提到的那样做,所以请有人帮帮我 我想手动插入条形码,当我按下按钮时,必须检查SQL Server数据库是否存在该条形码。如果没有,则必须将该条形码插入数据库,但如果该条形码已经存在,则必须给出一条消息,说明该条形码已经存在 在插入条形码的同时,我还在数据库中插入系统日期和时间。编辑 可以在按钮单击事件中编写的C代码 using System; using System.Collections.Generic; using System.ComponentM

我是C#编码新手,所以我试着像下面代码中提到的那样做,所以请有人帮帮我

我想手动插入条形码,当我按下按钮时,必须检查SQL Server数据库是否存在该条形码。如果没有,则必须将该条形码插入数据库,但如果该条形码已经存在,则必须给出一条消息,说明该条形码已经存在

在插入条形码的同时,我还在数据库中插入系统日期和时间。

编辑

可以在按钮单击事件中编写的C代码

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

namespace Barcode
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string strconn = @"Data Source=ASHWINI-LAPY\SQLEXPRESS;Initial Catalog=complete;Integrated Security=True;Pooling=False";
            SqlDataReader reader = null;

            SqlConnection conn = null;

            conn = new SqlConnection(strconn);
            conn.Open();

            DateTime Dt_Time = DateTime.Now;
            string Barcode = textBox1.Text;
            SqlCommand cmd = new SqlCommand("select Barcode from table3 where @Barcode='" + textBox1.Text + "'", conn);
            cmd.Parameters.AddWithValue("@Barcode", textBox1.Text);
            reader = cmd.ExecuteReader();
            if (reader != null && reader.HasRows)
            {
                //email exists in db do something

                MessageBox.Show("Barcode Already Exists!!");

            }
            else
            {
                string strquery = string.Format("insert into table3 values('{0}','{1}')", Barcode, Dt_Time);


                cmd = new SqlCommand(strquery, conn);


                int count = (int)cmd.ExecuteNonQuery();
                MessageBox.Show("Barcode:" + Barcode +
                                "\nTime" + Dt_Time);



            }
SQL过程

using (System.Data.SqlClient.SqlConnection cn = 
                    new System.Data.SqlClient.SqlConnection(@"Data Source=ASHWINI-LAPY\SQLEXPRESS;Initial Catalog=complete;Integrated Security=True;Pooling=False"+
                        "Integrated Security=True"))
{
       using (System.Data.SqlClient.SqlCommand cmd= new System.Data.SqlClient.SqlCommand("IsBarcodeCheckAndInsert", cn))
       {
            cmd.CommandType=CommandType.StoredProcedure ; 
            SqlParameter parm= new SqlParameter("@BarCode", cn",SqlDbType.VarChar) ;
            parm.Value="ALFKI";
            parm.Size=25;  
            parm.Direction =ParameterDirection.Input ;
            cmd.Parameters.Add(parm);
            SqlParameter parm2=new SqlParameter("@IsExists",SqlDbType.Int);
            parm2.Direction=ParameterDirection.Output;
            cmd.Parameters.Add(parm2); 
            cn.Open();
            cmd.ExecuteNonQuery();
            cn.Close();
            int IsExists = Convert.ToInt32(cmd.Parameters["@IsExists"].Value.ToString());
            if(IsExists ==0)
                 MessageBox.Show("Barcode Already Exists !!"); 
            else if(IsExists ==1)
                 MessageBox.Show("Barcode not Exists And Inserted In DataBase!!"); 

      }
}

代码有什么问题我检查你的代码没有问题。如果代码不起作用,你会得到什么错误


建议您在第二个查询中使用SQLParameter,在insert查询中使用SQLParameter,以避免SQLInjection攻击,了解更多详细信息,请检查:

您混淆了sql参数语法,这:

CREATE PROCEDURE [dbo].[IsBarcodeCheckAndInsert]
     (
       @BarCode AS VARCHAR(25),
       @IsExists AS INT out     )
 AS 
BEGIN
 IF EXISTS (SELECT * FROM table3 WHERE BarCode = @BarCode )
 BEGIN
     set @IsExists =1
 END
 ELSE
 BEGIN 
   Insert into table3 values(@BarCode ,getDate())
     set @IsExists =0
 END 
END
应该改成这样:

SqlCommand cmd = new SqlCommand("select Barcode from table3 where @Barcode='" + textBox1.Text + "'", conn);
cmd.Parameters.AddWithValue("@Barcode", textBox1.Text);
SqlCommand cmd = new SqlCommand("select Barcode from table3 where Barcode = @Barcode", conn);
cmd.Parameters.AddWithValue("@Barcode", textBox1.Text);
SqlCommand cmd = new SqlCommand("select Barcode from table3 where Barcode=@Barcode", conn);
基本上,您在查询中用参数名切换了列名

更新

对于“已经有一个打开的DataReader…”异常,使用块调整代码,如下所示:

SqlCommand cmd = new SqlCommand("select Barcode from table3 where @Barcode='" + textBox1.Text + "'", conn);
cmd.Parameters.AddWithValue("@Barcode", textBox1.Text);
SqlCommand cmd = new SqlCommand("select Barcode from table3 where Barcode = @Barcode", conn);
cmd.Parameters.AddWithValue("@Barcode", textBox1.Text);
SqlCommand cmd = new SqlCommand("select Barcode from table3 where Barcode=@Barcode", conn);
private void按钮1\u单击(对象发送者,事件参数e)
{

string strconn=“检查以下代码行:

private void button1_Click(object sender, EventArgs e)
{
    string strconn = "<connection string";

    using (SqlConnection conn = new SqlConnection(strconn))
    {
        bool readerHasRows = false; // <-- Initialize bool here for later use
        DateTime Dt_Time = DateTime.Now;
        string Barcode = textBox1.Text;
        string commandQuery = "SELECT Barcode FROM table3 WHERE Barcode = @Barcode";
        using(SqlCommand cmd = new SqlCommand(commandQuery, conn))
        {
            cmd.Parameters.AddWithValue("@Barcode", textBox1.Text);
            using(SqlDataReader reader = cmd.ExecuteReader())
            {
                // bool initialized above is set here
                readerHasRows = (reader != null && reader.HasRows);
            }
        }

        if (readerHasRows)
        {
            //email exists in db do something
            MessageBox.Show("Barcode Already Exists!!");
        }
        else
        {
            //Same as above
            string strquery = "INSERT INTO table3 VALUES (@Barcode, @DtTime)"; // '{0}','{1}')", Barcode, Dt_Time);
            using (SqlCommand cmd = new SqlCommand(strquery, conn))
            {
                cmd.Parameters.AddWithValue("Barcode", Barcode);
                cmd.Parameters.AddWithValue("DtTime", Dt_Time);
                int count = cmd.ExecuteNonQuery(); // this already the number of affected rows by itself
                // NOTE: '\n' doesn't really work to output a line break. 
                // Environment.NewLine should be used.
                MessageBox.Show("Barcode:" + Barcode + Environment.NewLine + "Time" + Dt_Time);
            }

        // code probably goes on ...

    } // end of using(SqlConnection...
} // end of method
如果
textBox1.Text
等于
“示例”
,则生成的SQL查询将是

string Barcode = textBox1.Text;
SqlCommand cmd = new SqlCommand("select Barcode from table3 where @Barcode='" + textBox1.Text + "'", conn);
cmd.Parameters.AddWithValue("@Barcode", textBox1.Text);
您可能希望将SqlCommand语句更改为:

Select Barcode from table3 where 'example'='example'

您可以这样做:

SqlCommand cmd = new SqlCommand("select Barcode from table3 where @Barcode='" + textBox1.Text + "'", conn);
cmd.Parameters.AddWithValue("@Barcode", textBox1.Text);
SqlCommand cmd = new SqlCommand("select Barcode from table3 where Barcode = @Barcode", conn);
cmd.Parameters.AddWithValue("@Barcode", textBox1.Text);
SqlCommand cmd = new SqlCommand("select Barcode from table3 where Barcode=@Barcode", conn);

关于

您可以在一个sql查询中使用-命令来完成此操作

在纯SQL中,它将如下所示:

SqlCommand cmd = new SqlCommand("select Barcode from table3 where Barcode=@Barcode", conn);
cmd.Parameters.AddWithValue("@Barcode", textBox1.Text);

首先也是最重要的是,“…where Barcode=@Barcode”(很高兴您使用了参数,同样适用于插入)我刚刚用c#更新了整个代码……如果对您有效,请不要忘记将其标记为已接受……您可能需要更改SQL语句的第一行(ALTER,存储过程名称):)我仍然看不到当您执行UpdateCustomerLogin时条形码是如何起作用的;)谢谢Alex!!,它现在可以工作了,但是当您输入sql数据库中存在的相同条形码时,它显示“已经有一个与此命令相关联的打开的Datareader,必须先关闭”执行此查询时会出现错误消息int count=(int)cmd.ExecuteNonQuery();@danyss我根据最常见的最佳实践(SqlConnection/Command/DataReader是IDisposable的,因此强烈建议使用块)通过重写代码来更新答案。