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 数据库是否存在该条形码。如果不存在,则必须将该条形码插入数据库,但如果它已经存在,则必须给出条形码已存在的消息!
除了插入条形码之外,我还在数据库中插入系统日期和时间。
最佳答案
编辑
可以在按钮单击事件中编写的 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 攻击,以便在此处查看更多详细信息:How does SQLParameter prevent SQL Injection?
关于c# - 如果不存在则插入否则显示消息 "Already exists",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11790710/