检查数据库中是否已存在用户数据 [英] Check if User Data is Already in Database

查看:81
本文介绍了检查数据库中是否已存在用户数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在当前代码中包括功能,以防止重复的添加被添加到数据库中.这样,如果某人已经注册了他们的姓名和电子邮件,则会弹出一条消息,提示他们已经将其信息添加到数据库中.我的表单使用asp.net,数据使用c#填充.我是否可以包含这样的内容: cmd.CommandText =从Table1中选择*,其中pName ='" + t1.Text +'和pEmail ='" + t2.Text +'"; 实现吗?

I would like to include functionality within the current code to prevent duplicate additions to be added to the database. This way if someone already registers their name and e-mail, a message instead will pop up to say that they have already added their information to the database. My form is using asp.net the data is populated using c#. Am I able to include something like this: cmd.CommandText = "select * from Table1 where pName='"+t1.Text+"' and pEmail='"+t2.Text+"'"; to achieve that?

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

推荐答案

我建议您先在INSERT语句之前进行SELECT查询.另外,您只能将电子邮件用作SELECT语句上的参数,而不能包含姓名,因为人们可能会使用相同的姓名.

I would suggest that you have a SELECT query first before INSERT statement. Also you can only use email as parameter on your SELECT statement and not include name since there are chance that persons have the same name.

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.
}

这篇关于检查数据库中是否已存在用户数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆