如何在插入新用户之前检查用户是否已经在数据库中 [英] How to check if user already in a database before inserting new user

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

问题描述

我有一个winform注册用户",现在在提交表单之前,我想检查数据库,如果用户输入的用户名在数据库中已更改.如果用户名存在,则应显示一个消息框,否则将提交表单.预先对tanx进行很大帮助的pls代码

I have a winform ''register user'', now before the form is submitted, i want to check the database if the username entered by the user is alredy in the database. if the username exist a messagebox should be displayed else the form is submitted.pls code wil b of great help tanx in advance

推荐答案

您可以使用SQL EXIST 检查表中是否存在UserID .
使用此命令检查用户是否已经存在:
You can use SQL EXIST to check whether the UserID exists in your table or not.
Use this command to check if the user is already exists:
DECLARE UserID VARCHAR(20) = 'test@test.com'
IF EXIST(SELECT * FROM tbUser WHERE UserID = @UserID)
BEGIN
    Print 'User Already Exist'
END
ELSE
BEGIN
    INSERT INTO tbUser VALUES(@UserID, 'Other Column Value')
END




--Amit




--Amit


创建一个SP并在数据集中返回结果,然后检查数据集是否有行,如果行数= 1则用户存在

这样的东西

Create a SP and return a result in dataset , then check if dataset has rows , if row count =1 then user exists

Something like this

Dataset dscheckuser=checkexists (txtusername.Text.Trim)
if(dscheckuser.table[0].rows.count > 0)
{
   // user exists 
}else
{
   // insert new user
}


一种实现方法是编写一个存储过程,该过程以用户ID作为参数并检查其是否在数据库中.
这是一个示例
One way to do it would be write a stored procedure that takes user ID as parameter and checks to see if its in the database.
Here is a sample
CREATE PROCEDURE usp_CheckUserExists
@UserID INT

AS
BEGIN

DECLARE @UserExists BIT

IF EXISTS(SELECT 1 FROM [Your User Table] WHERE UserID = @UserID)
BEGIN
    SET @UserExists = 1
END
ELSE
BEGIN
    SET @UserExists = 0
END

SELECT @UserExists AS UserExists

END



根据用户ID是否存在,SP返回true或false.您可以在应用程序中使用此结果,以在创建用户之前检查用户ID是否存在.



The SP returns true or false based on whether the user ID exists or not. You can take this result in your application to check if the user ID exists before creating the user.


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

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