2012-08-03 34 views
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數據庫是否存在該條形碼。如果沒有,它必須將該條形碼插入到數據庫中,但是如果它已經存在,則必須提供條形碼已存在的消息!

隨着插入條形碼我也插入系統日期和時間也在數據庫中。

+0

首先這將是'...其中條碼= @Barcode」(很高興你正在使用的參數,同樣適用於刀片太) – V4Vendetta 2012-08-03 06:58:00

+0

我只是更新整個代碼與C#.. – 2012-08-03 07:43:42

+0

不要忘記標記爲接受,如果它適合你... – 2012-08-03 07:44:00

回答

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 

代碼的哪些錯誤的代碼我檢查你的代碼代碼是好的..如果它不是在你工作結束什麼錯誤你重新獲得。

只是在插入查詢在你的第二個queryi.e recommandation 化妝使用的SqlParameter的也避免了更詳細的檢查這裏SQL注入攻擊的攻擊:How does SQLParameter prevent SQL Injection?

+0

我懷疑'where @Barcode = ...'會運行..? – V4Vendetta 2012-08-03 06:58:47

+0

@ V4Vendetta - y因爲我認爲沒有語法錯誤,代碼也沒有問題... – 2012-08-03 07:00:27

+0

您可能想要更改SQL語句(ALTER,存儲過程名稱)的第一行:) – rikitikitik 2012-08-03 07:10:51

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

基本上,您在查詢中使用參數名稱切換了列名稱。

UPDATE

至於 「已經有一個打開的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 

至少應該引導你走上正確的軌道。

+0

感謝Alex !!,它現在工作了,但是當你輸入相同的條形碼時存在於sql數據庫中,它顯示「已經有一個與此命令關聯的開放數據讀取器,必須先關閉」,執行此查詢時出現錯誤消息int count =(int)cmd.ExecuteNonQuery(); – danyss 2012-08-04 05:23:03

+0

@danyss我根據最常見的最佳實踐(SqlConnection/Command/DataReader是IDisposable,因此強烈建議使用塊)重寫您的代碼更新了答案。 – Alex 2012-08-06 06:55:54

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 [email protected]", conn); 
1

你可以這樣做:

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

問候

0

可以與Merge -command一個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); 
相關問題