VB Custom login page. Incorrect syntax near '.'. - sql

I am creating a custom log in page using VB in Visual Studio. Every time I try logging in, however, I get the following error:
"Incorrect syntax near '.'".
When I put in the wrong username/password combo it recognizes this, but when it is right it will get this error and fail to log in.
Private Function VerifyLogin(ByVal UserName As String) As Boolean
Try
Dim cnn As New Data.SqlClient.SqlConnection
cnn.ConnectionString = My.MySettings.Default.RedwoodConnectionString.Replace(";Integrated Security=True", ";Integrated Security=False") & UserSetting
Dim cmd As New Data.SqlClient.SqlCommand
cmd.Connection = cnn
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT COUNT (principal_id) FROM _ sys.database_principals WHERE(name = '" & UserName & "')"
cnn.Open()
Dim i As Integer
i = cmd.ExecuteScalar()
cnn.Close()
If (i > 0) Then Return True
Return False
Catch ex As Exception
System.Windows.Forms.MessageBox.Show("Error: " & ex.Message & vbNewLine & "Location: VerifyLogin() in Login.vb" & vbNewLine & "Returned value: False")
Return False
End Try
End Function

Look at this portion of your sql:
FROM _ sys.database_principals
See the mistake there? It thinks the _ is the full table name and sys is an alias. At this point, .database_principals is no longer valid, hence your error.
And while we're at it, you really need to fix the sql injection vulnerability!!

Related

VB.NET database is not in MS Access and login error

I use Microsoft Access to store the data. The register form shows msgbox that the data was saved but there isn't any data stored in the table when I check the table on Microsoft Access. Is it supposed to be like that or did I code wrong?
This is my register code
If PasswordTextBox.Text.Length >= 8 Then
Try
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database2.accdb")
Dim insert As String = "Insert into Table1 values('" & NameTextBox.Text & "','" & Staff_IDTextBox.Text & "','" & Phone_NoTextBox.Text & "','" & UsernameTextBox.Text & "','" & PasswordTextBox.Text & "');"
Dim cmd As New OleDbCommand(insert, conn)
conn.Open()
'cmd.ExecuteNonQuery()
MsgBox("Saved")
For Each txt As Control In Me.Controls.OfType(Of TextBox)()
txt.Text = ""
Next
Catch ex As Exception
MsgBox("Error")
End Try
Else
MsgBox("Password must be more than 8 character")
End If
End If
This is my login code
uname = UsernameTextBox.Text
pword = PasswordTextBox.Text
Dim query As String = "Select password From Table1 where name= '" & uname & "';"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database2.accdb"
Dim conn = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
conn.Open()
Try
pass = cmd.ExecuteScalar().ToString
Catch ex As Exception
MsgBox("Username does not exit")
End Try
If (pword = pass) Then
MsgBox("Login succeed")
Else
MsgBox("Login failed")
UsernameTextBox.Clear()
PasswordTextBox.Clear()
End If
There is an error at this line
pass = cmd.ExecuteScalar().ToString
It says:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Your "cmd.ExecuteNonQuery" is commented out, so the code will not save anything to the database.
You should close your connection after executing the INSERT command.
By default the table will have auto-numbered field as the first item in the table. You will need to remove this field from your table for that specific INSERT command to work.
Or you may need to use a slightly different INSERT command. It is useful to have auto-numbered ID fields in a table.
You probably should catch the exception and display ex.Message in your message box rather then "Error". The ex.Message will be much more helpful to you in debugging your program.
I have made all of these mistakes in my code at one time or other.
Your Login Code;
1)
You should catch the exception message and display in it a message box. This will make debugging faster.
The actual exception in your code will read "{"No value given for one or more required parameters."}
Your query is incorrect.
You should do the open, query, and close of the connection inside the Try-Catch block. Test for a null password afterwards to determine if the username does not exist.
Two separate answers provided, because you have two very separate questions.
Best wishes...

How to resolve the syntax error in UPDATE statement

What is wrong with this code? I did everything but I still get a
syntax error in UPDATE statement
Dim konfirmasi As String = MsgBox("Yakin data ingin diubah ?", vbQuestion + vbYesNo, "Konfirmasi")
If konfirmasi = vbYes Then
SqlQuery = "Update Tabel_Pengguna set " & _
"Username = '" & txtUsername.Text & "'," & _
"Password ='" & txtPassword.Text & "' where Kode_Pengguna = '" & txtKodePengguna.Text & "'"
CMD = New OleDbCommand(SqlQuery, DB)
CMD.ExecuteNonQuery()
MsgBox("Data berhasil diubah", vbInformation, "Informasi")
To make MsgBox work you would need to use the bitwise Or operator. This function returns a MsgBoxResult not a String. I suggest you change to the .net MessageBox and leave the old VB6 code behind.
Private Sub OPCode()
'Dim konfirmasi As MsgBoxResult = MsgBox("Yakin data ingin diubah ?", vbQuestion Or vbYesNo, "Konfirmasi")
Dim konfirmasi As DialogResult = MessageBox.Show("Yakin data ingin diubah ?", "Konfirmasi", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If konfirmasi = DialogResult.Yes Then
UpdatePengguna(txtUsername.Text, txtPassword.Text, txtKodePengguna.Text)
End If
End Sub
Keep connection local to the method where they are used so they can be closed and disposed with Using...End Using blocks. In this code both the connection and the command are included in the Using block; note the comma at the end of the first line of the Using.
Always use parameters to avoid Sql injection. With OleDb the names of the parameters are ignored but we use descriptive names to make reading the code easier. It is the order that matters. The order that the parameters appear in the Sql statement must match the order which the parameters are added to the parameters collection. You will have to check your database for the correct datatypes and field sizes. I suspect Kode_Pengguna might be a numeric type. If so, be sure the change the datatype of the passed in parameter PenKode.
I believe you are neglecting to open your connection unless your are passing around open connections (be still my heart!). Open the connection at the last minute, directly before the .Execute... and close it as soon as possible with the End Using.
Private Sub UpdatePengguna(UserName As String, Password As String, PenKode As String)
Using cn As New OleDbConnection(ConStr),
cmd As New OleDbCommand("Update Tabel_Pengguna Set [UserName] = #Username, [Password] = #Password Where Kode_Pengguna = #Kode;", cn)
cmd.Parameters.Add("#Username", OleDbType.VarChar, 100).Value = UserName
cmd.Parameters.Add("#Password", OleDbType.VarChar, 100).Value = Password
cmd.Parameters.Add("#Kode", OleDbType.VarChar, 100).Value = PenKode
cn.Open()
cmd.ExecuteNonQuery()
End Using
MessageBox.Show("Data berhasil diubah", "Informasi", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
I really hope you are not saving passwords as plain text.

Storing ID from SQL result

Im running the following code to tell if a user excists on a database - standard stuff. Obviously once the code is run a boolean true or false will be returned if there is a result. If a result is found i want to store the ID of the said result. Can anyone tell me how'd id go about doing this?
code:
Username = txtUserName.Text
Password = txtPassword.Text
dbConnInfo = "PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\Dave\Documents\techs.mdb"
con.ConnectionString = dbConnInfo
con.Open()
Sql = "SELECT * FROM techs WHERE userName = '" & Username & "' AND '" & Password & "'"
LoginCommand = New OleDb.OleDbCommand(Sql, con)
CheckResults = LoginCommand.ExecuteReader
RowsFound = CheckResults.HasRows
con.Close()
If RowsFound = True Then
MsgBox("Details found")
TechScreen.Show()
Else
MsgBox("Incorrect details")
End If
There are a lot of problems with the code snippet you posted. Hopefully, I can help you correct these problems.
In order to load the ID of the result you'll want to use SqlCommand.ExecuteScalar() as this is optimized to pull back one result from Sql.
As to what is wrong with your code, you're wide open to Sql Injection attacks and you should be using Parametrized Queries as shown in my sample below.
Public Function AddProductCategory( _
ByVal newName As String, ByVal connString As String) As Integer
Dim newProdID As Int32 = 0
Dim sql As String = _
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); " _
& "SELECT CAST(scope_identity() AS int);"
Using conn As New SqlConnection(connString)
Dim cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add("#Name", SqlDbType.VarChar)
cmd.Parameters("#Name").Value = newName
Try
conn.Open()
newProdID = Convert.ToInt32(cmd.ExecuteScalar())
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
Return newProdID
End Function
Source: MSDN

"Could not find installable ISAM" error in VB.NET

Im new to visual basic.. I would like to ask on how to fixed the problem "Could not find installable ISAM.". I used Visual Basic as programming language. I used MS access as the database. My program is to fetch data from access. This would be my code.
Imports System.Data.OleDb
Module Main
Dim mDataPath As String
Sub Main()
GetPupils()
Console.ReadLine()
End Sub
Private Function GetConnection() As OleDb.OleDbConnection
'return a new connection to the database5
Return New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Database Password=oNer00FooR3n0 " & "Data Source=" & "C:\Users\ERICO YAN\Desktop\MSaccessDB\MSaccessDB\oneroofccp.mdb")
End Function
Public Function GetPupils() As DataSet
Dim conn As OleDb.OleDbConnection = GetConnection()
Try
Dim ds As New DataSet 'temporary storage
Dim sql As String = "select * from SESSIONS" 'query
Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sql, conn) 'connection
Try
da.Fill(ds, "SESSIONS") 'fetch data from db
Finally
da.Dispose() 'in case something goes wrong
End Try
Dim startVal = 0 'first record
Dim endVal = ds.Tables(0).Rows.Count 'total number records
For var = startVal To endVal - 1 'display records
Console.WriteLine(ds.Tables(0).Rows(var).Item(0).ToString() + " " + ds.Tables(0).Rows(var).Item(1).ToString() + " " + ds.Tables(0).Rows(var).Item(3).ToString() + " " + ds.Tables(0).Rows(var).Item(3).ToString()) 'code for display id and name
Next
Return ds
Finally
conn.Close()
conn.Dispose()
End Try
End Function
End Module
I would like to know what is the cause of the error so that I can proceed to my program.. Thank you so much for the feedback..
You seem to be missing a delimiter after your password attribute.
I think you also need to use Jet OLEDB:Database Password=... instead (if indeed you have an access database protected with a password):
"Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=" & "C:\Users\ERICO YAN\Desktop\MSaccessDB\MSaccessDB\oneroofccp.mdb;" _
& "Jet OLEDB:Database Password=oNer00FooR3n0;"
Missing ; delimiter here:
...Password=oNer00FooR3n0 " & "Data Sourc...
Needs to be
...Password=oNer00FooR3n0 " & ";Data Sourc...
Also just Password instead of Database Password.
Initially, i too got this sort of error, but when i wrote the connection string in a single line (i mean without using [& _] or breaking in 2 lines, then this worked properly.
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\USER1\Desktop\MSaccessDB\MSaccessDB\my_database_file.mdb;Database Password=MyPassword"
Hope this helps.
Mukesh L.

OleDB Exception: Could not find installable ISAM

Dim con As New OleDb.OleDbConnection
Sub connecttodatabase(ByVal fileselected As String)
Dim databasepassword
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source = " & fileselected
Try
con.Open()
Catch e As OleDb.OleDbException
If e.Message = "Not a valid password." Then
Console.WriteLine("Database has a password. Please enter password to continue.")
databasepassword = Console.ReadLine()
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source = " & fileselected & ";JetOLEDB:Database Password=" & databasepassword & ";"
con.Open()
End If
errorid = 1
Finally
End Try
End Sub
The error I am encountering occurs at the second con.Open() when I try to connect to a .mdb database file which I created in access, the function correctly tells me I have a password, but then once I enter my password I get the error defined in the title, and I have no idea why. Any help would be greatly appreciated.
Try this instead:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;User Id=admin;Password=YOURPASS;
Also, what exception are you getting from the first call to open the db? Maybe it's same problem: the ISAM isn't present. Try reinstalling MDAC:
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=78cac895-efc2-4f8e-a9e0-3a1afbd5922e