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

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...

Related

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.

Insert into database in vb not working

I have the below snippet of code whenever I try registering the username exist part seems to be executed even for a username that doesn't exist in the database. Don't know where am wrong here any help will be appreciated.
'Connecting to SQL Database and executing Query------------------------------------------
Dim Strconn As String = "Data Source=.\SQLEXPRESS; Database=QuizDB; Integrated Security = true"
Dim Strcmd As String = "INSERT INTO reg_info(uname,pass,fname,lname,dob,course,college) VALUES ('" & user_name.Text & "','" & con_pass.Text & "', '" & first_name.Text & "', '" & last_name.Text & "', '" & dob.Text & "', '" & course.Text & "', '" & college.Text & "');"
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Dim sqlcmd As SqlCommand
sqlconn = New SqlConnection(Strconn)
Try
sqlconn.Open()
Catch ex As Exception
MsgBox("Could not connect to DataBase. Application will close now!", vbCritical, "Database Error")
End
End Try
sqlcmd = New SqlCommand(Strcmd, sqlconn)
da.SelectCommand = sqlcmd
sqlcmd.Dispose()
sqlconn.Close()
'Exception Handling-----------------------
Dim exc As Exception = Nothing
Try
da.Fill(ds)
Catch ex As Exception
exc = ex
Finally
If Not (exc) Is Nothing Then
MsgBox("User Name Already Exist. Please select a different User Name!", vbExclamation, "Already Exist")
user_name.Focus()
Else
MsgBox("Registration Successful.", vbInformation, "Successful")
Me.Close()
Login.Show()
End If
End Try
Here is a refactor of your code with some helpful guidance. I think this will compile, but if it does not, then you can do a little homework to figure out what is missing.
Try
' the USING block guarantees that the object's Close() and Dispose() methods are fired automatically when you exit the block
Using sqlconn As New SqlConnection("Data Source=.\SQLEXPRESS; Database=QuizDB; Integrated Security = true")
Using sqlcmd As SqlCommand = sqlconn.CreateCommand
With sqlcmd
.CommandType = CommandType.Text
' parameterized query to protect against SQL injection
.CommandText = "INSERT INTO reg_info(uname,pass,fname,lname,dob,course,college) VALUES (#username, #password, #firstname, #lastname, #dob, #course, #college)"
With .Parameters
.Clear()
.AddWithValue("#username", user_name.Text)
.AddWithValue("#password", con_pass.Text)
.AddWithValue("#firstname", first_name.Text)
.AddWithValue("#lastname", last_name.Text)
.AddWithValue("#dob", dob.Text)
.AddWithValue("#course", course.Text)
.AddWithValue("#college", college.Text)
End With
.ExecuteScalar() ' Actually executes the SQL command
End With
End Using
End Using
MsgBox("Registration successful")
Catch ex As Exception
' Any error in the TRY block will automatically jump to herem and the "ex" object will be an Exception object with populated properties
MsgBox("User name already exists. Error from database is " & ex.Message)
End Try

Why this error .. command text was not set to command object

conn.Open()
Try
Dim update As New OleDbCommand
update.Connection = conn
update.CommandText = " UPDATE O_name SET fname= '" & Name1.Text & "' WHERE ID = '" & ID.Text & "'"
update.ExecuteNonQuery()
MsgBox("done")
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
conn.Close()
there is always Error
" Command Text was not set to command object "
what's the reason
please don't talk about parametrized query cause i'm asking about this specifically
A quick google for the error message has a link to this page as the first search result, where someone writes:
The problem was EvaluateAsExpression was not set to true..its working now..thanks again for the help :)
What kept you from using Google and finding it as quicky as I did?

Vb.Net Error This OleDbTransaction has completed; it is no longer usable

I have a VB.Net desktop application that does three tasks. First, it inserts data into Table A, then Table B, and finally, it copies a file from one directory to another. I am using transactions for my database inserts. In the event that an error occurs in any of the three steps, I want to roll back the transaction. The problem is, when a specific scenario occurs, and I roll back the transaction, i get the following error:
This OleDbTransaction has completed; it is no longer usable.
This happens if both database inserts succeed but the file copy fails. I'm not sure if I've set up my transactions wrong or what. If anyone has any feedback, let me know. Oh and the database I'm using is Oracle 10g. Bellow is my code:
Private Sub insertNew(ByVal doc As someObject)
Dim conString As String
conString = "Provider=MSDAORA.1;" _
& "User ID=" & My.Settings.User & ";" _
& "Password=" & My.Settings.Password & ";" _
& "Data Source=" & My.Settings.DatabaseName & ";" _
& "Persist Security Info=False"
Dim insertString1 As String
Dim insertString2 As String
Dim transaction As OleDbTransaction
insertString1 = "INSERT INTO mySchema.myTable1(ID_DOC, ID_DOC_FORMAT) VALUES (?,?)"
insertString2 = "INSERT INTO mySchema.myTable2(LOCATION_ID, PK_DOCUMENT) VALUES (?,?)"
Dim conn As New OleDbConnection(conString)
Try
Dim nextValue As Integer
'this function is a database call to get next sequence from database
nextValue = readData()
Using conn
conn.Open()
transaction = conn.BeginTransaction()
Dim command1 As New OleDbCommand
Dim command2 As New OleDbCommand
Try
With command1
.Connection = conn
.Transaction = transaction
.CommandType = CommandType.Text
.CommandText = insertString1
.Parameters.Add("#IdDoc", OleDbType.VarChar).Value = doc.IdDoc
.Parameters.Add("#IdDocFormat", OleDbType.VarChar).Value = doc.IdDocFormat
.ExecuteNonQuery()
End With
Catch exCMD1 As Exception
Throw New ApplicationException("unable to insert into table DM_DOCUMENTS (" & exCMD1.Message & ")")
End Try
Try
With command2
.Connection = conn
.Transaction = transaction
.CommandType = CommandType.Text
.CommandText = insertString2
.Parameters.Add("#IndPyramid", OleDbType.VarChar).Value = doc.IndPyramid
.Parameters.Add("#LocationId", OleDbType.Integer).Value = doc.LocationId
.ExecuteNonQuery()
End With
Catch exCMD2 As Exception
Throw New ApplicationException("unable to insert into table DM_LOCATION_DOC_XREF (" & exCMD2.Message & ")")
End Try
If copyFiles(doc.IdDoc) = True Then
transaction.Commit()
'everything was a success, so commit
Else
'error copying file, so roll back.
' If the error originates from here, it will throw to the next catch, and that is where I get the described error
Throw New ApplicationException("unable to copy to New Path")
End If
End Using
Catch ex As Exception
If transaction IsNot Nothing Then
'error occurs here if it came from trying to copy files code block
transaction.Rollback()
End If
Throw
Finally
conn.Close()
conn.Dispose()
End Try
End Sub
Never mind. It was because I was trying to rollback the transaction outside of the correct Try Catch statement. After you exit the using statement, the db stuff gets disposed of and this will cause the error. I just redid my try catch statements and now it works fine.
If you check whether the connection associated to that transaction is null or not then you are done.
Only apply commit or rollback if the connection object of the transaction is not null
eg.
OleDBTransaction testTransaction = someOleDBConnection.BeginTransaction();
//your all transactional codes
if(testTransaction.Connection != null)
testTransaction.Rollback() OR testTransaction.Commit() //Based on your requirement
you can try the different Isolation Level of transaction.
transaction = conn.BeginTransaction(IsolationLevel.ReadUncommitted)
https://msdn.microsoft.com/en-us/library/system.data.isolationlevel(v=vs.110).aspx

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

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!!