简体   繁体   中英

Check if user exists in database in ASP.NET

My problem is that I want to check if username in registration page already exists in database to prevent multiple same names but got an error

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: Incorrect syntax near '*'.

Here is my code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if(IsPostBack)           //tworzymy Zapytanie wraz z połączeniem z bazą
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["registrationConn"].ConnectionString);
            conn.Open();
            string sprawdz = "Wybierz count (*) from Uzytkownicy where Nazwa_uzytkownika='"+un.Text+"'";
            SqlCommand com = new SqlCommand(sprawdz, conn);
            int temp = Convert.ToInt32((String)com.ExecuteScalar().ToString());  <----The error moment
            if(temp==1)
            {
                Response.Write("Uzytkownik o podanej nazwie już istnieje.");
            }
            conn.Close();
        } 

Please, can anyone help me?

Try to replace

string sprawdz = "Wybierz count (*) from Uzytkownicy where Nazwa_uzytkownika='"+un.Text+"'";

with

string sprawdz = "select count (*) from Uzytkownicy where Nazwa_uzytkownika='"+un.Text+"'";

I am not a Polish speaker but checked on google that Wybierz is a Polish word which means select ( Link )

So logically and syntactically it should be select not Wybierz

I would recommend in this case to do this per stored procedure with SQL.

Why? Stored procedures are compiled once and stored in executable form, so procedure calls are quick and efficient. Executable code is automatically cached and shared among users . This lowers memory requirements and invocation overhead.

So Code like this:

SqlCommand cmd = new SqlCommand("CheckIfUserExists",conn);
cmd.CommandType=CommandType.StoreProcedure;
cmd.Parameters.AddWithValue("@UserName",un.Text);
cmd.Parameters.AddWithValue("@IsExists",0);
int rowAffected=cmd.ExecuteNonQuery();
// rowAffected contains your Result

And procedure like this :

CREATE PROCEDURE  CheckIfUserExists   
(    
    @UserName Varchar(50),  
    @IsExists INT OUTPUT   
)   
AS      

If exists (select Nazwa_uzytkownika from Uzytkownicy where Nazwa_uzytkownika = @username)   
Begin

Set @IsExists = 1

End     
Else   
begin

Set @IsExists = 0

End

Return @IsExists

Hope so i got this right with polish.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM