C#if语句检查用户是否在数据库中激活 [英] C# if statement to check if user excist in database

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

问题描述

您好

我正在尝试学习C#并且似乎无法弄清楚要编写哪些代码来检查用户名(和电子邮件)是否已经在数据库中存在... 

im trying to learn C# and cant seem to figure out what code to write to check if username ( and email ) already excist in datbase.. 

所以这是我5个小时后...在这里寻求帮助:

so this is me 5 hours later ... writing for help in here :

我知道我需要一些if语句,所以如果用户名已经兴奋然后是真/假

i know i need an somekind of if statement so if username already excist then true / false

只是不知道如何执行代码。

just donno how to actualy do the code.

private void button1_Click(object sender, EventArgs e)
        {
         if (txtusername.Text == "" & txtEmail.Text != "" & txtpassword.Text != "" & txtcpass.Text != "")
        {
            cn.Open();
            cmd.CommandText = "insert into Login (username,email,password,cpass) values ('" + this.txtusername.Text + "','" + this.txtEmail.Text + "','" + this.txtpassword.Text + "','" + this.txtcpass.Text + "')";
            cmd.ExecuteNonQuery();
            cmd.Clone();
            MessageBox.Show("Record inserted!");
            cn.Close();
            txtusername.Text = "";
            txtEmail.Text = "";
            txtpassword.Text = "";
            txtcpass.Text = "";
            loadlist();
            }
            }        

推荐答案

在我看来,这个功能在数据库级别实现更可靠:将用户名和电子邮件定义为Login表的复合主键。这取决于数据库的类型(MSSQL,Access等),可以在设计
表时完成。

然后你将收到一个可以用 try-catch 语句拦截的异常。

Then you will receive an exception that can be intercepted with try-catch statement.

顺便说一下,你不必调用克隆。使用参数化查询和
使用语句更安全。

By the way, you do not have to call Clone. And it is safer to use parameterised queries and using statements.


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

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