c#
  • asp.net
  • 2016-10-26 131 views 0 likes 
    0

    我想在當前代碼中包含功能以防止將重複添加添加到數據庫中。這樣,如果某人已經註冊了他們的姓名和電子郵件,則會彈出消息說他們已經將他們的信息添加到了數據庫中。我的表單使用asp.net,數據使用c#填充。我能夠包括這樣的東西:cmd.CommandText = "select * from Table1 where pName='"+t1.Text+"' and pEmail='"+t2.Text+"'";來實現這一目標嗎?檢查用戶數據是否已經在數據庫中

    C#代碼:

    using System.Data.OleDb; 
    using System.Configuration; 
    
    public partial class Default2 : System.Web.UI.Page 
    { 
        protected void Page_Load(object sender, EventArgs e) 
        { 
    
        } 
    
        protected void Button1_Click(object sender, EventArgs e) 
        { 
         OleDbConnection con = new OleDbConnection(); 
         con.ConnectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString2"].ToString(); 
         con.Open(); 
         OleDbCommand cmd = new OleDbCommand(); 
         cmd.CommandText = "insert into[Table1](pName)values(@nm)"; 
         cmd.Parameters.AddWithValue("@nm", TextBox1.Text); 
         cmd.CommandText = "insert into[Table1](pEmail)values(@nm)"; 
         cmd.Parameters.AddWithValue("@nm", TextBox2.Text); 
         cmd.Connection = con; 
         int a = cmd.ExecuteNonQuery(); 
         if (a>0) 
         { 
          Label1.Text = "Inserted Sucessfully!"; 
         } 
        } 
    } 
    
    +0

    簡而言之,是的,你可以用'count(*)'來返回記錄數。但更好的是使用'Parameters'而不是字符串concat – Prisoner

    +1

    使try-catch代碼圍繞你的代碼。如果插入重複數據,它將通過sql異常捕獲異常並顯示消息 –

    +0

    謝謝!我會試一下! – penmas

    回答

    0

    我建議你有一個SELECT查詢第一INSERT語句之前。您也只能在您的SELECT語句中使用電子郵件作爲參數,並且不包含名稱,因爲有可能人員具有相同的名稱。

    string query = "SELECT COUNT(ID) FROM tblUsers WHERE email = @email 
    int count = db.ExecuteReader(query);  
    
    
    if (count > 0){ 
        return "email is already in use"; 
    } else { 
        //Call the insert statement here with try catch inside. In this way you can handle if error occur on the execution itself. 
    } 
    
    +0

    在這種情況下,如何解決查詢不是int的問題? – penmas

    +0

    我的錯誤,如果我用var而不是int來聲明查詢。 select count應該返回int(記錄數)。 – bogzy

    +0

    更新了上面的代碼。這個想法在那裏,你可能需要添加一些修改艱難。 – bogzy

    0

    你可以使用這個,但我使用SQL Server 2014 ..Try這個.. 架構

    CREATE TABLE [dbo].[Dummy](
        [id] [bigint] IDENTITY(1,1) NOT NULL, 
        [Name] [nvarchar](50) NULL, 
    ) 
    

    和查詢

    if not exists(select 1 from Dummy where Name='akash') 
        insert into Dummy(Name) values('aka') 
    

    這是沒有回報的單查詢排在int a = cmd.ExecuteNonQuery();

    方法2: 創建一個獨特的CONSTRAINT並使用try catch發現沒有重複的行被插入。

    ALTER TABLE [dbo].[Dummy] ADD CONSTRAINT [uc_Name] UNIQUE 
    NONCLUSTERED 
    (
        Name ASC 
    ) 
    
    相關問題