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数据库是否存在该条形码。如果没有,它必须将该条形码插入数据库,但如果它已经存在,则必须发出条形码已经存在的消息!
除了插入条形码,我还在数据库中插入系统日期和时间。
答案 0 :(得分: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 Procdure
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
代码有什么问题我检查你的代码是没问题的..如果它不能解决你的错误,你会得到什么错误。
只是建议在第二个查询中使用SQLParame在插入查询中也可以避免SQLInjection攻击以获取更多详细信息,请点击此处:How does SQLParameter prevent SQL Injection?
答案 1 :(得分: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
至少应该引导你走上正轨。
答案 2 :(得分: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);
答案 3 :(得分:1)
您可以这样做:
SqlCommand cmd = new SqlCommand("select Barcode from table3 where Barcode=@Barcode", conn);
cmd.Parameters.AddWithValue("@Barcode", textBox1.Text);
此致
答案 4 :(得分: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);