You are on page 1of 24

Data Developer Center

Sign in
United States (English)
HomeLibraryLearnDownloadsSupportCommunityForums
Data Developer Center > Data Platform Development Forums > ADO.NET Managed
Providers > Database secure login to program
Ask a question
Search Forums:
Database secure login to program
Monday, August 14, 2006 10:16 PM
blanc0

0
Sign In to Vote
Hi,
I am creating a VB.Net program and know basic VB programming. The program will at
first ask you to login. I want an admin who can change his password and also add
users. I am not sure how to do this. I know how to access SQL databases but not how
to make the program check the database each time a user inputs a login and them
direct him to his account or how he can change his password without being able to
access that of others.

If anyone could give me a word of advice thats easy to understand I would be very
grateful.
ReplyQuote
Answers
Monday, August 14, 2006 10:23 PM
ahmedilyas

0
Sign In to Vote
Sure

basically you check the credentials (username/password) that the user entered and
query it in the database like:

SELECT [ID] FROM TableName WHERE username = username AND [password] = password

now a record will be returned (more specifically just the ID column) if it matches,
which means that yes, the user exists and they entered the correct
username/password then based upon this, you can do whatever you like, such as open
another form

To change the password, again its simple, you do a check with the current password
they entered against the password stored in the database, and if it succeeds will
it go ahead and update the password.
Storing passwords must be secure, a good way would be doing an MD5 - which is a one
way hash meaning you cannot decrypt the hash in any way.

So when they enter a password, be sure to encrypt it in MD5 first then do the
query, assuming the database holds the MD5 based passwords (as they should do)

As for doing "admin" stuff, I guess in the database design you can have a field in
the users table with a data type of bit (1 or 0) to indicate if the current user is
an admin ( 1 ) or not ( 0 ) then based upon this, direct them to the appropriate
form or whatever.

you basically need, in the admin system, another form where they can add users,
then pretty much place the appropriate fields you want to store in the database and
generate an insert statement like:

INSERT INTO TableName ( column1, column2.....) VALUES (value1, value2.....)

be sure to make sure that when you do an ExecuteQuery, to see how many rows where
effected, this would indicate a success on insertion if its more than 0

does this help?

ReplyQuote
Tuesday, August 15, 2006 2:33 AM
ahmedilyas

0
Sign In to Vote
look at the SQLConnection, SQLCommand and perhaps SqlDataAdapter classes:

http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx

http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx

http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx

examples are enclosed

ReplyQuote
Wednesday, August 16, 2006 1:51 AM
ahmedilyas

0
Sign In to Vote
Well again there are many ways of doing this.

you could fill a dataset with the data of the correct user, then check to see if
there is a record in the dataset, if there is then we know that they exist in the
database and authentication was successful, with the added value of "customizing"
the form with their user details for example.

Or if you dont want to customize the details on your form (displaying their name
for example) then you can return back a value (true/false bit value) from the
stored procedure for example (if you are using one)

I believe the first option would be better, so change your query to select all
columns/fields and fill the dataset. Example:

Dim theDataset as new DataSet()


dim theSQLCommand as new SqlCommand("SELECT [ID], firstname, lastname FROM
tableName WHERE username = '" + Me.theUsername.Text + "' AND [password] = '" +
theEncryptedPassword + "'")
..
..
dim theDataAdapter as new SqlDataAdapter(theSQLCommand)
theDataAdapter.Fill(theDataSet)

if theDataSet.Tables(0).Rows.Count > 0 Then


'We have the user authenticated, do whatever you want now. All details stored in
the Table, first row (theDataSet.Tables(0).Rows(0))
else
'incorrect, user doesnt exist or login invalid
end if

ReplyQuote
Sunday, December 03, 2006 1:00 AM
ahmedilyas

0
Sign In to Vote
the code provided earlier or snippets help you do this.

Encrypting strings to MD5:

http://msdn2.microsoft.com/en-us/library/system.security.cryptography.md5.aspx

import the System.Data, System.Data.SqlClient and the System.Security and


System.Security.Cryptography namespaces
Checking if username/password exists in database

private function DoCheckUser(byval username as string, byval hashedPassword as


string) as boolean

Dim success as Boolean = false

Dim theSqlCommand as new SqlCommand("SELECT [ID] FROM [TableName] WHERE [username]


= @username AND [password] = @password", new SqlConnection(connectionString))

Dim theUsernameParam as new SqlParameter("@username", username)

Dim thePasswordParam as new SqlParameter("@password", password)

theSqlCommand.Parameters.Add(theUsernameParam)

theSqlCommand.Parameters.Add(thePasswordParam)

theSqlCommand.Connection.Open()

Dim theReader as SqlDataReader =


theSqlCommand.ExecuteReader(CommandBehavior.CloseConnection)

if theReader.HasRows then 'we have data, user exists

success = true

end if

theSqlCommand.Connection.Close()

return success

end function

private function GetMD5Hash(byval rawString as String) as String

Dim theMD5 as MD5 = System.Security.Cryptography.MD5.Create()

return
BitConverter.ToString(theMD5.ComputeHash(System.Text.Encoding.Default.GetBytes(rawS
tring))).Replace("-", String.Empty)

end function
private sub CmdLogin_Click(byval sender as object, byval e as eventargs) handles
CmdLogin.Click

If Me.DoCheckUser(Me.txtUserName.Text, Me.GetMD5Hash(Me.txtPassword.Text)) =
true then

MessageBox.Show("you are authenticated")

else

MessageBox.Show("username/password does not exist or is invalid")

end if

end sub

This will check to see if the username and password given via textbox input exists
in the database.

Add new user into the database

private sub CmdCreateNewUser_Click(byval sender as object, byval e as EventArgs)


handles CmdCreateNewUser.Click

if Me.DoCreateUser(Me.txtUserName.Text, Me.GetMD5Hash(Me.txtPassword.Text)) then

MessageBox.Show("User account created successfully")

else

MessageBox.Show("User account not created")

end if

end sub

private function DoCreateUser(byval username as String, byval encryptedPassword as


String) as boolean

Dim theSqlCommand as new SqlCommand("INSERT INTO [TableName] (username, password)


VALUES (@username, @password)", new SqlConnection(connectionString))

Dim theUsernameParam as new SqlParameter("@username", username)

Dim thePasswordParam as new SqlParameter("@password", encryptedPassword)

theSqlCommand.Parameters.Add(theUsernameParam)
theSqlCommand.Parameters.Add(thePasswordParam)

try

theSqlCommand.Connection.Open()

theSqlCommand.ExecuteNonQuery()

theSqlCommand.Connection.Close()

return true

catch ex as SqlException

MessageBox.Show("Error: " & Environment.NewLine & ex.ToString())

return false

end try

end function

this should insert a new user into the database

Changing password of existing user

private sub CmdChangeDetails_Click(byval sender as object, byval e as eventargs)


handles CmdChangeDetails.Click

if Me.DoChangeUserDetails(Me.txtUsername.Text,
Me.GetMD5Hash(Me.txtPassword.Text), Me.GetMD5Hash(Me.txtNewPassword.Text)) then

MessageBox.Show("Details updated")

else

MessageBox.Show("Could not update details")

end if

end sub

private function DoChangeUserDetails(byval username as String, byval


oldEncryptedPassword as String, byval newEncryptedPassword as String) as Boolean

Dim success as Boolean = false


Dim theSqlCommand as new SqlCommand("UPDATE [TableName] SET [password] =
@newPassword WHERE [username] = @username AND [password] = @password", new
SqlConnection(connectionString))

Dim theUsernameParam as new SqlParameter("@username", username)

Dim theOldPasswordParam as new SqlParameter("@password", oldEncryptedPassword)

Dim theNewPasswordParam as new SqlParameter("@newPassword", newEncryptedPassword)

theSqlCommand.Parameters.Add(theUsernameParam)

theSqlCommand.Parameters.Add(theOldPasswordParam)

theSqlCommand.Parameters.Add(theNewPasswordParam)

theSqlCommand.Connection.Open()

Dim rowsAffected as Integer = theSqlCommand.ExecuteNonQuery()

theSqlCommand.Connection.Close()

if rowsAffected > 0 then

success = true

else

success = false

end if

return success

end function

this should update the user's password if it exists in the database (username and
password)

remember these are guidelines you can follow and use and can be modified to your
needs
ReplyQuote
Sunday, December 03, 2006 2:42 AM
ahmedilyas

0
Sign In to Vote
the connectionstring is a connection string to the database which you will need to
create. Typically this is how to connect to SQL Server, the connectionstring:

"Data Source=.;Trusted_Connection=true;Initial Catalog=DatabaseNameHere;"

if you are using SQLExpress then change the Data Source part to this:

Data Source=.\SQLExpress

ReplyQuote
Sunday, December 03, 2006 3:11 AM
ahmedilyas

0
Sign In to Vote
have you read the links I had supplied? Tried also following the tooltip help that
comes up in intellisense, which guides you on what parameter it expects for you to
give that method?

you just give the string the previous response into the part where it says in bold
"connectionString". Example:

Dim theSqlCommand as new SqlCommand("SELECT [ID] FROM [TableName] WHERE [username]


= @username AND [password] = @password", new SqlConnection("Data Source=.;Initial
Catalog=MyDatabase;Trusted_Connection=true;"))

of course you need to replace the Initial catalog to the name of the database you
are trying to access.

take a look at this too, this is the second parameter that the SqlCommand expects:

http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx

ReplyQuote
All Replies
Monday, August 14, 2006 10:23 PM
ahmedilyas

0
Sign In to Vote
Sure

basically you check the credentials (username/password) that the user entered and
query it in the database like:
SELECT [ID] FROM TableName WHERE username = username AND [password] = password

now a record will be returned (more specifically just the ID column) if it matches,
which means that yes, the user exists and they entered the correct
username/password then based upon this, you can do whatever you like, such as open
another form

To change the password, again its simple, you do a check with the current password
they entered against the password stored in the database, and if it succeeds will
it go ahead and update the password.

Storing passwords must be secure, a good way would be doing an MD5 - which is a one
way hash meaning you cannot decrypt the hash in any way.

So when they enter a password, be sure to encrypt it in MD5 first then do the
query, assuming the database holds the MD5 based passwords (as they should do)

As for doing "admin" stuff, I guess in the database design you can have a field in
the users table with a data type of bit (1 or 0) to indicate if the current user is
an admin ( 1 ) or not ( 0 ) then based upon this, direct them to the appropriate
form or whatever.

you basically need, in the admin system, another form where they can add users,
then pretty much place the appropriate fields you want to store in the database and
generate an insert statement like:

INSERT INTO TableName ( column1, column2.....) VALUES (value1, value2.....)

be sure to make sure that when you do an ExecuteQuery, to see how many rows where
effected, this would indicate a success on insertion if its more than 0

does this help?

ReplyQuote
Tuesday, August 15, 2006 1:29 AM
blanc0

0
Sign In to Vote
Thanks, its been very helpful. But I dont quite understand how when you click the
login button the check is done. Eg. pseudocode would be
If user.textbox=database and pass.textbox=database then
form1.visible=true
else msgbox(error)

How would I do the =database part, from VB language to the SQL language you gave
me?

Thanks
ReplyQuote
Tuesday, August 15, 2006 2:33 AM
ahmedilyas

0
Sign In to Vote
look at the SQLConnection, SQLCommand and perhaps SqlDataAdapter classes:

http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx

http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx

http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx

examples are enclosed

ReplyQuote
Wednesday, August 16, 2006 1:35 AM
blanc0

0
Sign In to Vote
Ive managed to create a program that looks in the database for the ID and password,
and display them on 2 textboxes. But I dont know how to run the query when the
button is clicked and how to know if the output is true or false.
Thanks.
ReplyQuote
Wednesday, August 16, 2006 1:51 AM
ahmedilyas

0
Sign In to Vote
Well again there are many ways of doing this.

you could fill a dataset with the data of the correct user, then check to see if
there is a record in the dataset, if there is then we know that they exist in the
database and authentication was successful, with the added value of "customizing"
the form with their user details for example.

Or if you dont want to customize the details on your form (displaying their name
for example) then you can return back a value (true/false bit value) from the
stored procedure for example (if you are using one)
I believe the first option would be better, so change your query to select all
columns/fields and fill the dataset. Example:

Dim theDataset as new DataSet()


dim theSQLCommand as new SqlCommand("SELECT [ID], firstname, lastname FROM
tableName WHERE username = '" + Me.theUsername.Text + "' AND [password] = '" +
theEncryptedPassword + "'")
..
..
dim theDataAdapter as new SqlDataAdapter(theSQLCommand)
theDataAdapter.Fill(theDataSet)

if theDataSet.Tables(0).Rows.Count > 0 Then


'We have the user authenticated, do whatever you want now. All details stored in
the Table, first row (theDataSet.Tables(0).Rows(0))
else
'incorrect, user doesnt exist or login invalid
end if

ReplyQuote
Monday, November 20, 2006 1:32 AM
Tamalero

0
Sign In to Vote
ahmedilyas wrote:
Well again there are many ways of doing this.

you could fill a dataset with the data of the correct user, then check to see if
there is a record in the dataset, if there is then we know that they exist in the
database and authentication was successful, with the added value of "customizing"
the form with their user details for example.

Or if you dont want to customize the details on your form (displaying their name
for example) then you can return back a value (true/false bit value) from the
stored procedure for example (if you are using one)

I believe the first option would be better, so change your query to select all
columns/fields and fill the dataset. Example:

Dim theDataset as new DataSet()


dim theSQLCommand as new SqlCommand("SELECT [ID], firstname, lastname FROM
tableName WHERE username = '" + Me.theUsername.Text + "' AND [password] = '" +
theEncryptedPassword + "'")
..
..
dim theDataAdapter as new SqlDataAdapter(theSQLCommand)
theDataAdapter.Fill(theDataSet)

if theDataSet.Tables(0).Rows.Count > 0 Then


'We have the user authenticated, do whatever you want now. All details stored in
the Table, first row (theDataSet.Tables(0).Rows(0))
else
'incorrect, user doesnt exist or login invalid
end if

just to extend this information ..

once the login as been set, is there a way to "optain" certain informations ( like
rows for certain flags )

like to see "whos admin" "superuser" "user" and "visitor" ?

like diferent access levels.?

CODE:

Dim thingie2 As String

thingie2 = "select * from usuarios where nip='" + usuario + "'"

dataadapter = New Data.OleDb.OleDbDataAdapter(thingie2, coneccion)

dataadapter.SelectCommand.ExecuteNonQuery()

dataadapter.Update(dataset, "usuarios")

fila = dataset.Tables("usuarios").Rows(0)

'3,4,5,6 admin, moduser, fotos, sonido

paginaprincipal.Show()

Select Case mierditaparacase

Case fila(3) = 1

paginaprincipal.admin_run()

Case fila(4) = 1 And fila(5) = 1 And fila(6) = 1

paginaprincipal.modpass()

paginaprincipal.modfotos()

paginaprincipal.modsonidos()
Case fila(4) = 1 And fila(5) = 1 And fila(6) = 0

paginaprincipal.modpass()

paginaprincipal.modfotos()

Case fila(4) = 1 And fila(5) = 0 And fila(6) = 1

paginaprincipal.modpass()

paginaprincipal.modsonidos()

Case fila(4) = 1 And fila(5) = 0 And fila(6) = 0

paginaprincipal.modpass()

Case fila(4) = 0 And fila(5) = 1 And fila(6) = 0

paginaprincipal.modfotos()

Case fila(4) = 0 And fila(5) = 0 And fila(6) = 1

paginaprincipal.modsonidos()

Case fila(4) = 0 And fila(5) = 1 And fila(6) = 1

paginaprincipal.modfotos()

paginaprincipal.modsonidos()

End Select

paginaprincipal.ToolStripStatusLabel1.Text = " Bienvenido usuario:" + usuario

Me.Close()

paginaprincipal = form2 wich acts as main menu after the login procedure, depending
the "flags" in the database of the loged user,

is the actions it will do..

modfotos as example, will run an script that turns on the "photo" menu of the main
page.

and after ejecuting everything, it closes the login screen leaving the main menu
with the menus unlocked.

Im not sure if the CASE is correctly used, since last time I used CASE.... was in
borland c++ and they use a totally diferent way to declare and use.

ReplyQuote
Sunday, December 03, 2006 12:12 AM
jcnconnect
0
Sign In to Vote
I'm not really getting this.
ReplyQuote
Sunday, December 03, 2006 12:18 AM
ahmedilyas

0
Sign In to Vote
ok. Can you explain exactly what you dont understand so we can help you better?
ReplyQuote
Sunday, December 03, 2006 12:40 AM
jcnconnect

0
Sign In to Vote
I created a tabel with three coloms ( username, password, status ( admin,
superuser,user,guest )) but i don't know how to encrypt the password to MD5 and i
don't know how to search the database for the username and check the username for
its password and the usernames status. I also don't know how to create a new user
and a new password with the username, or change a current username and its password
an status.

ReplyQuote
Sunday, December 03, 2006 1:00 AM
ahmedilyas

0
Sign In to Vote
the code provided earlier or snippets help you do this.

Encrypting strings to MD5:

http://msdn2.microsoft.com/en-us/library/system.security.cryptography.md5.aspx

import the System.Data, System.Data.SqlClient and the System.Security and


System.Security.Cryptography namespaces

Checking if username/password exists in database

private function DoCheckUser(byval username as string, byval hashedPassword as


string) as boolean

Dim success as Boolean = false


Dim theSqlCommand as new SqlCommand("SELECT [ID] FROM [TableName] WHERE [username]
= @username AND [password] = @password", new SqlConnection(connectionString))

Dim theUsernameParam as new SqlParameter("@username", username)

Dim thePasswordParam as new SqlParameter("@password", password)

theSqlCommand.Parameters.Add(theUsernameParam)

theSqlCommand.Parameters.Add(thePasswordParam)

theSqlCommand.Connection.Open()

Dim theReader as SqlDataReader =


theSqlCommand.ExecuteReader(CommandBehavior.CloseConnection)

if theReader.HasRows then 'we have data, user exists

success = true

end if

theSqlCommand.Connection.Close()

return success

end function

private function GetMD5Hash(byval rawString as String) as String

Dim theMD5 as MD5 = System.Security.Cryptography.MD5.Create()

return
BitConverter.ToString(theMD5.ComputeHash(System.Text.Encoding.Default.GetBytes(rawS
tring))).Replace("-", String.Empty)

end function

private sub CmdLogin_Click(byval sender as object, byval e as eventargs) handles


CmdLogin.Click

If Me.DoCheckUser(Me.txtUserName.Text, Me.GetMD5Hash(Me.txtPassword.Text)) =
true then

MessageBox.Show("you are authenticated")

else
MessageBox.Show("username/password does not exist or is invalid")

end if

end sub

This will check to see if the username and password given via textbox input exists
in the database.

Add new user into the database

private sub CmdCreateNewUser_Click(byval sender as object, byval e as EventArgs)


handles CmdCreateNewUser.Click

if Me.DoCreateUser(Me.txtUserName.Text, Me.GetMD5Hash(Me.txtPassword.Text)) then

MessageBox.Show("User account created successfully")

else

MessageBox.Show("User account not created")

end if

end sub

private function DoCreateUser(byval username as String, byval encryptedPassword as


String) as boolean

Dim theSqlCommand as new SqlCommand("INSERT INTO [TableName] (username, password)


VALUES (@username, @password)", new SqlConnection(connectionString))

Dim theUsernameParam as new SqlParameter("@username", username)

Dim thePasswordParam as new SqlParameter("@password", encryptedPassword)

theSqlCommand.Parameters.Add(theUsernameParam)

theSqlCommand.Parameters.Add(thePasswordParam)

try

theSqlCommand.Connection.Open()

theSqlCommand.ExecuteNonQuery()
theSqlCommand.Connection.Close()

return true

catch ex as SqlException

MessageBox.Show("Error: " & Environment.NewLine & ex.ToString())

return false

end try

end function

this should insert a new user into the database

Changing password of existing user

private sub CmdChangeDetails_Click(byval sender as object, byval e as eventargs)


handles CmdChangeDetails.Click

if Me.DoChangeUserDetails(Me.txtUsername.Text,
Me.GetMD5Hash(Me.txtPassword.Text), Me.GetMD5Hash(Me.txtNewPassword.Text)) then

MessageBox.Show("Details updated")

else

MessageBox.Show("Could not update details")

end if

end sub

private function DoChangeUserDetails(byval username as String, byval


oldEncryptedPassword as String, byval newEncryptedPassword as String) as Boolean

Dim success as Boolean = false

Dim theSqlCommand as new SqlCommand("UPDATE [TableName] SET [password] =


@newPassword WHERE [username] = @username AND [password] = @password", new
SqlConnection(connectionString))

Dim theUsernameParam as new SqlParameter("@username", username)


Dim theOldPasswordParam as new SqlParameter("@password", oldEncryptedPassword)

Dim theNewPasswordParam as new SqlParameter("@newPassword", newEncryptedPassword)

theSqlCommand.Parameters.Add(theUsernameParam)

theSqlCommand.Parameters.Add(theOldPasswordParam)

theSqlCommand.Parameters.Add(theNewPasswordParam)

theSqlCommand.Connection.Open()

Dim rowsAffected as Integer = theSqlCommand.ExecuteNonQuery()

theSqlCommand.Connection.Close()

if rowsAffected > 0 then

success = true

else

success = false

end if

return success

end function

this should update the user's password if it exists in the database (username and
password)

remember these are guidelines you can follow and use and can be modified to your
needs

ReplyQuote
Sunday, December 03, 2006 2:33 AM
jcnconnect

0
Sign In to Vote
Ok I made a form with two text boxes. One named txtUserName and the other named
txtPassword. I added the code, but i got three errors can you help me solve these
errors.

error1). Error 1 Name 'connectionString' is not declared.

error2 ). Error 2 Name 'password' is not declared.

error3). Error 3 Handles clause requires a WithEvents variable defined in the


containing type or one of its base types.

here is my code

Imports System.Data

Imports System.Data.SqlClient

Imports System.Security

Imports System.Security.Cryptography

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles MyBase.Load

End Sub

Private Function DoCheckUser(ByVal username As String, ByVal hashedPassword As


String) As Boolean

Dim success As Boolean = False

Dim theSqlCommand As New SqlCommand("SELECT [ID] FROM [TableName] WHERE [username]


= @username AND [password] = @password", New SqlConnection(connectionString))

Dim theUsernameParam As New SqlParameter("@username", username)

Dim thePasswordParam As New SqlParameter("@password", password)

theSqlCommand.Parameters.Add(theUsernameParam)

theSqlCommand.Parameters.Add(thePasswordParam)

theSqlCommand.Connection.Open()

Dim theReader As SqlDataReader =


theSqlCommand.ExecuteReader(CommandBehavior.CloseConnection)
If theReader.HasRows Then 'we have data, user exists

success = True

End If

theSqlCommand.Connection.Close()

Return success

End Function

Private Function GetMD5Hash(ByVal rawString As String) As String

Dim theMD5 As MD5 = System.Security.Cryptography.MD5.Create()

Return
BitConverter.ToString(theMD5.ComputeHash(System.Text.Encoding.Default.GetBytes(rawS
tring))).Replace("-", String.Empty)

End Function

Private Sub CmdLogin_Click(ByVal sender As Object, ByVal e As EventArgs) Handles


CmdLogin.Click

If Me.DoCheckUser(Me.txtUserName.Text, Me.GetMD5Hash(Me.txtPassword.Text)) = True


Then

MessageBox.Show("you are authenticated")

Else

MessageBox.Show("username/password does not exist or is invalid")

End If

End Sub

End Class

ReplyQuote
Sunday, December 03, 2006 2:42 AM
ahmedilyas
0
Sign In to Vote
the connectionstring is a connection string to the database which you will need to
create. Typically this is how to connect to SQL Server, the connectionstring:

"Data Source=.;Trusted_Connection=true;Initial Catalog=DatabaseNameHere;"

if you are using SQLExpress then change the Data Source part to this:

Data Source=.\SQLExpress

ReplyQuote
Sunday, December 03, 2006 3:02 AM
jcnconnect

0
Sign In to Vote
how do i create a connection string.
ReplyQuote
Sunday, December 03, 2006 3:11 AM
ahmedilyas

0
Sign In to Vote
have you read the links I had supplied? Tried also following the tooltip help that
comes up in intellisense, which guides you on what parameter it expects for you to
give that method?

you just give the string the previous response into the part where it says in bold
"connectionString". Example:

Dim theSqlCommand as new SqlCommand("SELECT [ID] FROM [TableName] WHERE [username]


= @username AND [password] = @password", new SqlConnection("Data Source=.;Initial
Catalog=MyDatabase;Trusted_Connection=true;"))

of course you need to replace the Initial catalog to the name of the database you
are trying to access.

take a look at this too, this is the second parameter that the SqlCommand expects:

http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx

ReplyQuote
Tuesday, December 12, 2006 4:16 AM
Brianwiz

0
Sign In to Vote
Hello,
I want to first thank you i understand the code.. But im having major problems
understanding the error. Im a VB6.0 going to this transition and well its rough.

I get an error

theSqlCommand.Connection.Open()

An error has occurred while establishing a connection to the server. When


connecting to SQL Server 2005, this failure may be caused by the fact that under
the default settings SQL Server does not allow remote connections. (provider: Named
Pipes Provider, error: 40 - Could not open a connection to SQL Server)

To me it seems something with the SQL and the program when i set it up. But im
unsure.

any help would be appreciated

ReplyQuote
Tuesday, December 12, 2006 4:39 AM
Brianwiz

0
Sign In to Vote
I just created a login forum for with web developer and that works.

I have made sure sql is a go on the computer through the links provided in other
sections

.
ReplyQuote
Friday, December 14, 2007 4:06 PM
drew4663

0
Sign In to Vote
Ok, I have read through thias and it seems pretty good but I am a little confused
on some things. i was wondering if I could get some clarification. I am not
getting any syntax errors but I am getting the MessageBox.Show("Sorry,
username/password details were incorrect")

Code Block
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim theConnectionString As New
SqlClient.SqlConnection("Server=.\SQLExpress;Database=Master;Trusted_Connection=Yes
;")
Dim theSqlCommand As New SqlClient.SqlCommand("SELECT [LoginID] FROM
[Login] WHERE [username] = @username AND [password] =@password",
theConnectionString)

Dim theUsername As New SqlClient.SqlParameter("@username",


SqlDbType.VarChar)
theUsername.Value = "username"
Dim thePassword As New SqlClient.SqlParameter("@password",
SqlDbType.VarChar)
thePassword.Value = "password"
theSqlCommand.Parameters.Add(theUsername)
theSqlCommand.Parameters.Add(thePassword)

'open the connection


theSqlCommand.Connection.Open()
Dim theDataReader As SqlClient.SqlDataReader =
theSqlCommand.ExecuteReader(CommandBehavior.CloseConnection)

Dim theLoginType As Object = Nothing


If theDataReader.HasRows Then
theDataReader.Read()
'the user exists!! Lets get the logintype:
theLoginType = theDataReader("loginType")
End If
theSqlCommand.Connection.Close()

If theLoginType = Nothing Then


MessageBox.Show("Sorry, username/password details were incorrect")
Else
MessageBox.Show("Login successful")
End If
End Sub

Any ideas?

ReplyQuote
Need Help with Forums? (FAQ)
My Forum Links
Sign In To Forums
Forums Home
Browse Forums Users

Related Topics
= Unanswered = Answered
Designing a secure login form that connects to a database on my ...
How to secure a database to prevent customer from changing ...
how to secure sql server database
Secure SQL Login Info
putting user accounts on the database
returning values
Problems deploying Express database app in common app data path
Starting SQL Server BEFORE login
A user login page using sql
Simple login form
Statistics
Started: 8/14/2006
Last Reply: 12/3/2006
Helpful Votes: 0
Replies: 17
Views: 8,656
� 2011 Microsoft. All rights reserved.Terms of Use|Trademarks|Privacy Statement|
Contact Us|Manage Your Profile

You might also like