2
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);



            }

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

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

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

4

5 回答 5

2

编辑

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

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!!"); 

      }
}

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

代码有什么问题我检查你的代码代码很好..如果它在你身上不起作用,你会遇到什么错误。

只是建议在您的第二个查询中使用 SQLParameter,即在插入查询中也可以避免 SQLInjection 攻击以查看更多详细信息:SQLParameter如何防止 SQL 注入?

于 2012-08-03T06:55:47.650 回答
1

你可以这样做:

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

问候

于 2012-08-03T07:08:53.613 回答
1

你混合了你的 sql 参数语法,这个:

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);

基本上,您在查询中用参数名称切换了列名。

更新

至于“已经有一个打开的DataReader ...”异常,请使用using块调整代码(在“最佳实践”方法中),如下所示:

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

至少应该带领你走上正轨。

于 2012-08-03T07:00:54.283 回答
1

查看这些代码行:

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

如果textBox1.Text等于"example",则生成的 SQL 查询将是

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

您可能希望将 SqlCommand 语句更改为:

SqlCommand cmd = new SqlCommand("select Barcode from table3 where Barcode=@Barcode", conn);
于 2012-08-03T07:01:29.603 回答
0

您可以使用Merge命令在一个 sql 查询中执行此操作。

在纯 SQL 中,它看起来像:

merge table3 WITH(HOLDLOCK) as target
    using (SELECT @Barcode, @DtTime)
        as source (Barcode, DtTime)
        on target.Barcode = @Barcode
    when not matched then
        insert ( Barcode, DtTime)
        values ( @Barcode, @DtTime);
于 2013-08-14T14:25:16.303 回答