检查用户名是否在c#中的数据表中

时间:2020-12-20 15:49:22

I'm working on VS2010 c#.

我正在研究VS2010 c#。

I have a datatable containing username and passwords:

我有一个包含用户名和密码的数据表:

____________
andy | 1234
joni | 5678
lara | 4567

How do I form a function that will see what the user entered in a textbox and review if it is in the database or not?

如何形成一个函数,该函数将查看用户在文本框中输入的内容并查看它是否在数据库中?

2 个解决方案

#1


4  

You could write a SQL Function and do something like:

您可以编写SQL函数并执行以下操作:

CREATE FUNCTION [dbo].[CheckUserExists] (@User NVARCHAR(50))
RETURNS BIT
AS 
BEGIN
DECLARE @RetVal INT

SELECT @RetVal = COUNT(User.UserId)
FROM
    Users
WHERE
    Users.Username = @User

IF @RetVal > 0 
BEGIN
   RETURN 1
END
    RETURN 0
END

Then in your C# program you could use ADO.NET and do:

然后在您的C#程序中,您可以使用ADO.NET并执行:

private bool UserExists(string username) {
     SqlCommand cmd  = new SqlCommand("CheckUserExists", conn);

 cmd.CommandType = CommandType.StoredProcedure;

 cmd.Parameters.Add(new SqlParameter("@User", username));

     SqlDataReader reader = cmd.ExecuteReader(); // execute the function

     // return the response from the reader (1 if it is true, 0 for false)
}

You could then call the function by doing:

然后,您可以执行以下操作来调用该函数

 var userExists = UserExists("YourUser");

http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson07.aspx

#2


1  

You can do a select statement on a datatable which will return an array of DataRows's.

您可以对数据表执行select语句,该语句将返回DataRows的数组。

DataRow[] foundRows = DataTable.Select("username = andy");
if(foundRows.Length > 0)
{
Console.WriteLine("Username exists");
}

#1


4  

You could write a SQL Function and do something like:

您可以编写SQL函数并执行以下操作:

CREATE FUNCTION [dbo].[CheckUserExists] (@User NVARCHAR(50))
RETURNS BIT
AS 
BEGIN
DECLARE @RetVal INT

SELECT @RetVal = COUNT(User.UserId)
FROM
    Users
WHERE
    Users.Username = @User

IF @RetVal > 0 
BEGIN
   RETURN 1
END
    RETURN 0
END

Then in your C# program you could use ADO.NET and do:

然后在您的C#程序中,您可以使用ADO.NET并执行:

private bool UserExists(string username) {
     SqlCommand cmd  = new SqlCommand("CheckUserExists", conn);

 cmd.CommandType = CommandType.StoredProcedure;

 cmd.Parameters.Add(new SqlParameter("@User", username));

     SqlDataReader reader = cmd.ExecuteReader(); // execute the function

     // return the response from the reader (1 if it is true, 0 for false)
}

You could then call the function by doing:

然后,您可以执行以下操作来调用该函数

 var userExists = UserExists("YourUser");

http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson07.aspx

#2


1  

You can do a select statement on a datatable which will return an array of DataRows's.

您可以对数据表执行select语句,该语句将返回DataRows的数组。

DataRow[] foundRows = DataTable.Select("username = andy");
if(foundRows.Length > 0)
{
Console.WriteLine("Username exists");
}