Error when updating SQLite database using VB.Net - sql

Trying to get this code to work so that it will update my SQLite database. Keep getting an error saying that an end of statement is expected error BC30205. I cannot see what i am missing! This is my first ever attempt at an update statement in SQL so i may have missed something obvious! I have marked the line of code i am having the error with with an arrow!
Public Partial Class Change_Password
Public Sub New()
' The Me.InitializeComponent call is required for Windows Forms designer support.
Me.InitializeComponent()
'
' TODO : Add constructor code after InitializeComponents
'
End Sub
Dim SQLconnect As New System.Data.SQLite.SQLiteConnection()
Dim SQLcommand As System.Data.SQLite.SQLiteCommand
Dim SQLreader As System.Data.SQLite.SQLiteDataReader
Dim Password1 As String = ""
Dim Password2 As String = ""
Public Class Password
Public shared usernamechange As String = ""
End Class
Sub Cmd_NextClick(sender As Object, e As EventArgs)
If Trim(txt_Password_Box.Text) = "" Then
MsgBox("Please enter a password")
Else
Password1 = txt_Password_Box.Text
txt_Password_Box.Text = ""
txt_Password_Box.Focus
lbl_Instruction.Text = "Please re-enter the exact same password!"
cmd_Submit.Visible = True
cmd_Next.Visible = False
Me.AcceptButton = cmd_Submit
End If
End Sub
Sub Change_PasswordLoad(sender As Object, e As EventArgs)
cmd_Submit.Visible = False
Me.AcceptButton = cmd_Next
SQLconnect.ConnectionString = "Data Source=KCD.s3db;"
SQLconnect.Open()
End Sub
Sub Cmd_SubmitClick(sender As Object, e As EventArgs)
If Trim(txt_Password_Box.Text) = "" Then
MsgBox("Please enter the password again")
Exit Sub
Else
Password2 = txt_Password_Box.Text
txt_Password_Box.Text = ""
End If
If Password1 = Password2 Then
SQLcommand = SQLconnect.CreateCommand
------> SQLcommand.CommandText = "UPDATE Staff SET Password = '" & password1 & "' WHERE '" Username = "' & password.usernamechange & '"""
SQLcommand.Dispose()
MsgBox("Your password has been changed",vbInformation,"Password Changed")
Me.Close
Else
MsgBox("Passwords do not match. Please try again.")
txt_Password_Box.Focus
cmd_Submit.Visible = False
cmd_Next.Visible = True
Password1 = ""
Password2 = ""
lbl_Instruction.Text = "Please enter a new password!"
Me.AcceptButton = cmd_Next
End If
End Sub
End Class
Hope someone can help me! Thanks

This line doesn't seem right. Change
SQLcommand.CommandText = "UPDATE Staff SET Password = '" & password1 & "' WHERE '" Username = "' & password.usernamechange & '"""
to
SQLcommand.CommandText = "UPDATE Staff SET Password = '" & password1 & "' WHERE Username = '" & password.usernamechange & "'"
BTW, concatenating strings like that leads to being vulnerable to SQL Injection.

Related

in vb.net error Command text was not set for the command object

I have a program in vb.net where I need data inserted into the database. When I run this code I get an error:
Command text was not set for the command object
Here is the code I have:
Private Sub InsertRelease(strRelease As String, rowInserted As Boolean)
On Error GoTo errH
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strPath As String
Dim intImportRow As Integer
Dim objType As String
Dim strUsername, strPassword, strTable, strDatabase, strDsn, strSystem, strNewSql, sqlStr As String
Dim intRecsAffected As Integer
Dim boolRowInserted As Boolean
strDsn = ComboBox1.Text
strSystem = txtSystem.Text
strUsername = txtUser.Text
strPassword = txtPassword.Text
If con.State <> 1 And strUsername <> "" And strPassword <> "" Then
con.Open("{iSeries As ODBC Driver};System=" + strSystem + ";Dsn=" + strDsn + "; Uid=" + strUsername + "; Pwd=" + strPassword + ";")
Else
MessageBox.Show("Please enter the correct UserName And Password")
txtUser.Focus()
con = Nothing
End If
sqlStr = "insert into jobscopedb.ppusrfs (search_key_uf,DATA_ITEM_UF, NUMERIC_VALUE_UF) values (strRelease,'81 AB',0);"
strNewSql = ""
con.Execute(strNewSql, intRecsAffected)
con.Close()
con = Nothing
boolRowInserted = (intRecsAffected > 0)
If (boolRowInserted) Then
MessageBox.Show("Release " + strRelease + " added")
Else
MessageBox.Show("Release " + strRelease + "not added")
End If
Exit Sub
errH:
MsgBox(Err.Description)
con = Nothing
End Sub
The following demonstrates what your code might look like using ADO.net.
Pass the connection string directly to the constructor of the connection and pass the command text and connection to the constructor of the command. Open the connection and execute the command. ExecuteNonQuery returns rows affected.
Always use parameters to avoid sql injection.
Private Sub InsertRelease(strRelease As String)
Dim intRecsAffected As Integer
Dim strDsn = ComboBox1.Text
Dim strSystem = txtSystem.Text
Dim strUsername = txtUser.Text
Dim strPassword = txtPassword.Text
'Validate Input
If strUsername = "" OrElse strPassword = "" Then
MessageBox.Show("Please enter the correct UserName And Password")
txtUser.Focus()
Exit Sub
End If
Using con As New OdbcConnection($"{{iSeries As ODBC Driver}};System={strSystem};Dsn={strDsn}; Uid={strUsername}; Pwd={strPassword};"),
cmd As New OdbcCommand("insert into jobscopedb.ppusrfs (search_key_uf, DATA_ITEM_UF, NUMERIC_VALUE_UF) values (#Release,'81 AB',0);", con)
cmd.Parameters.Add("#Release", OdbcType.VarChar).Value = strRelease
con.Open()
intRecsAffected = cmd.ExecuteNonQuery
End Using 'Closes and disposes the connection and command even it there is an error
If intRecsAffected = 1 Then
MessageBox.Show("Release " + strRelease + " added")
Else
MessageBox.Show("Release " + strRelease + "not added")
End If
End Sub

VB How to Clear existing items in listview

I am trying to search the information from the sql server then show at the listview. Everytime I click search it won't clear the existing records based on the past time searching. I've tried item.clear, it will only show me the new search but it won't clear all the existing records. Can someone help please?
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim strNameSource As String
Dim strPhoneSource As String
Dim strBothSource As String
If OpenConnect() = True Then
Try
If ChkCustName.Checked = True Then
strNameSource = "SELECT TCI.strLastName + ', ' + TCI.strFirstName AS strName,TCI.strPhoneNumber,CONVERT(VARCHAR,TCI.dtmCheckIn, 101),CONVERT(VARCHAR,TCI.dtmCheckOut,101),TRT.strRoomType,TR.strRoom FROM TCheckInInfo AS TCI,TRoom AS TR,TRoomType AS TRT WHERE TCI.intRoomID = TR.intRoomID AND TR.intRoomTypeID = TRT.intRoomTypeID AND intCheckInStatusID = 1 AND TCI.strLastName ='" & txtLastName.Text & "'"
SearchReservation(strNameSource)
ElseIf ChkPhoneNumber.Checked = True Then
strPhoneSource = "SELECT TCI.strLastName + ', ' + TCI.strFirstName AS strName,TCI.strPhoneNumber,CONVERT(VARCHAR,TCI.dtmCheckIn, 101),CONVERT(VARCHAR,TCI.dtmCheckOut,101),TRT.strRoomType,TR.strRoom FROM TCheckInInfo AS TCI,TRoom AS TR,TRoomType AS TRT WHERE TCI.intRoomID = TR.intRoomID AND TR.intRoomTypeID = TRT.intRoomTypeID AND intCheckInStatusID = 1 AND TCI.strPhoneNumber ='" & txtPhoneNumber.Text & "'"
SearchReservation(strPhoneSource)
ElseIf ChkCustName.Checked = True And ChkPhoneNumber.Checked = True Then
strBothSource = "SELECT TCI.strLastName + ', ' + TCI.strFirstName AS strName,TCI.strPhoneNumber,CONVERT(VARCHAR,TCI.dtmCheckIn, 101),CONVERT(VARCHAR,TCI.dtmCheckOut,101),TRT.strRoomType,TR.strRoom FROM TCheckInInfo AS TCI,TRoom AS TR,TRoomType AS TRT WHERE TCI.intRoomID = TR.intRoomID AND TR.intRoomTypeID = TRT.intRoomTypeID AND intCheckInStatusID = 1 AND TCI.strPhoneNumber ='" & txtPhoneNumber.Text & "' AND TCI.strLastName ='" & txtLastName.Text & "'"
SearchReservation(strBothSource)
End If
txtLastName.Clear()
txtPhoneNumber.Clear()
Catch excError As Exception
WriteLog(excError)
'End program
Application.Exit()
End Try
End If
End Sub
Private Sub SearchReservation(ByVal strSource As String)
Dim itemcollection(100) As String
Dim Row As Integer
Dim Column As Integer
Dim ListViewItem As New ListViewItem
lstReservation.Items.Clear()
Try
cmd = New OleDb.OleDbCommand(strSource, cnn)
Adapter = New OleDb.OleDbDataAdapter(cmd)
Adapter.Fill(Ds, "Table")
'Now adding the Items in Listview
If Ds.Tables(0).Rows.Count = 0 Then
' Something went wrong. warn user
MessageBox.Show(Me, "Could not find the Customer", "Customer finding Error", _
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
lstReservation.BeginUpdate()
For Row = 0 To Ds.Tables(0).Rows.Count - 1
For Column = 0 To Ds.Tables(0).Columns.Count - 1
itemcollection(Column) = Ds.Tables(0).Rows(Row)(Column).ToString()
Next
ListViewItem = New ListViewItem(itemcollection)
lstReservation.Items.Add(ListViewItem)
Next
lstReservation.EndUpdate()
End If
Catch excError As Exception
WriteLog(excError)
'End program
Application.Exit()
End Try
End Sub
Lots of issues with your code, but I'll focus on your immediate issue.
You keep filling the DataSet with new tables, but you keep using the original table that is still in position zero of the DataSet.
I would venture a guess that you need to clear the rows of your DataTable:
If Ds.Tables.Contains("Table") Then
Ds.Tables("Table").Rows.Clear()
End If
lstReservation.Items.Clear()
of just clear any tables there:
Ds.Tables.Clear()
lstReservation.Items.Clear()

VB.net COMExeption was unhandled

I am creating a user login system using vb.net and MS access. I am unsure what is going wrong with my system and I receive the error message "Item cannot be found in the collection corresponding to the requested name or ordinal" The error is coming up in the section "User.Find(Username)" on the first line of the DO loop. Here is my code:
Public Class Login
Dim LoginError As String ' This will tell the user what is wrong with his login
Public Function Login()
Dim DBConn As New ADODB.Connection ' This is how we tell visual studio
'how to connect to our database
Dim User As New ADODB.Recordset 'We pass our argument through our recordset
Dim Username As String 'This will be our "Query"
Dim strUserDB As String 'This get sets to the email field in our database.
Dim strPassDB As String 'Same as above just for the password
Dim blnUserFound As Boolean 'I will be using a "DO" loop so I will use
'this as my condition
DBConn.Open("Provider = Microsoft.Jet.OLEDB.4.0;" & _
"Data Source = '" & Application.StartupPath & "\UserDetails2000.mdb'")
'The inverted comas in the dataOuce statement as itt keeps the location of your
'file as one string.
User.Open("tblUserDetails", DBConn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic)
'This is my table 'This is my connection 'These are some settings
blnUserFound = False
Login = False
Username = "User = '" & txtEmail.Text & "'" 'This tells the database to find the email field
'Equivilent to what was entered in the textbox
Do
User.Find(Username) 'This is the full statement that sends my 'Query' to the record set
If User.BOF = False And User.EOF = False Then
'BOF = Begining of file, EOF = End of file, it tests whether the database has
'reached its sentinal value, if it hasent then the username has been found, If it has,
'the username has been found.
strUserDB = User.Fields("Email").Value.ToString
'"Email" is my table field. I am setting strUserDB to the username field of my table
strPassDB = User.Fields("Password").Value.ToString
If strUserDB <> txtEmail.Text Then
User.MoveNext()
'This IF statement handles different CASE usernames, Example, admin and AdMiN
'We use this if statement to differentiate between different CASE letters
Else
blnUserFound = True
If strPassDB = txtPassword.Text Then
User.Close()
DBConn.Close()
Return True
Else
LoginError = "Invalid Password"
User.Close()
DBConn.Close()
Return False
End If
End If
Else
LoginError = "Invalid Username"
User.Close()
DBConn.Close()
Return False
End If
Loop Until blnUserFound = True
LoginError = "Invalid Username"
User.Close()
DBConn.Close()
Return False
End Function
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
If Login() = True Then
MessageBox.Show("Login Succesful", "Login Status")
Else
MessageBox.Show(LoginError, "Login Status")
End If
End Sub
End Class
Verify that tblUserDetails contains a column named User.
Maybe User is also a reserved keyword in Access so try setting Username as:
Username = "[User] = '" & txtEmail.Text & "'"

Struggling with basic VB.net. Variable addition

I'm trying to set up my form program so if the user fails to login 3 times (linked to a database), it closes the program. However, I'm a kinda crap at programming and I can't get the variable to actually hold the addition I'm trying to use?
Private Sub Login_Click(sender As Object, e As EventArgs) Handles Login.Click
Dim uname, pass As String
Dim attempt As Integer = 0
' Warns the user if they have missed out login information.
If UserNameBox.Text = "" Or PasswordBox.Text = "" Then
MessageBox.Show("Please ensure you have entered your username and password", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
uname = UserNameBox.Text
pass = PasswordBox.Text
GetFilteredData("username = '" & uname & "' AND password = '" & pass & "'")
If CountRecords() = 1 Then
MsgBox("Logged In!")
Else
MsgBox("Incorrect Credentials!")
attempt = attempt + 1 ' <-- Main Issue is here
If attempt = 4 Then
Application.Exit()
End If
End If
End If
End Sub
Any help would be amazing. Thanks :D
You're declaring on the attempt varible inside the Login_Click event handler. Hence, each time the Login_Click event is raised, you are initializing it to 0.
Dim attempt As Integer = 0
Try to move it to outer scope, for example make it a member of the Class.
This should work. If you want to have variable accessible from all subs, just take it out too root of class.
Private attempt As Integer = 0
Private Sub Login_Click(sender As Object, e As EventArgs) Handles Login.Click
Dim uname, pass As String
' Warns the user if they have missed out login information.
If UserNameBox.Text = "" Or PasswordBox.Text = "" Then
MessageBox.Show("Please ensure you have entered your username and password", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
uname = UserNameBox.Text
pass = PasswordBox.Text
GetFilteredData("username = '" & uname & "' AND password = '" & pass & "'")
If CountRecords() = 1 Then
MsgBox("Logged In!")
Else
MsgBox("Incorrect Credentials!")
attempt = attempt + 1 ' <-- Main Issue is here
If attempt = 4 Then
Application.Exit()
End If
End If
End If
End Sub

Error when I set a radio button to be checked by default

I have a radio button in my VB.NET dll that I wan't to be checked by default. There is a total of 3 radio buttons in this group. Under its properties I set Checked = true. I verified the code was there, this is all the form generated code for the radio button:
Me.rdbProductPC.AutoSize = True
Me.rdbProductPC.Checked = True
Me.rdbProductPC.Font = New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.rdbProductPC.Location = New System.Drawing.Point(49, 12)
Me.rdbProductPC.Name = "rdbProductPC"
Me.rdbProductPC.Size = New System.Drawing.Size(45, 17)
Me.rdbProductPC.TabIndex = 1
Me.rdbProductPC.TabStop = True
Me.rdbProductPC.Text = "P&&C"
Me.rdbProductPC.UseVisualStyleBackColor = True
For some reason I get this error when I start the application:
An error occurred creating the form. See Exception.InnerException for details. The error is: ExecuteReader requires an open and available Connection. The connection's current state is closed.
Nothing has changed besides the one line adjusting the checked value. Any idea what could be causing this?
This is the code for my GetProducts() method. The error arises after the call to ExecuteReader() but I cannot see the code for this. If my g_strSQL = pc_mis_busunit_product_relate_summary it executes fine. But when g_strSQL = pc_mis_busunit_product_relate_summary '','','N' it errors out.
That being said, if I leave the radio button unchecked by default and then check it later while the program is running it will go into this same method and g_strSQL will look like pc_mis_busunit_product_relate_summary '','','N' and it will work fine.
Private Sub GetProducts(ByVal ProductList As ListBox)
Dim g_strSQL As String
ProductList.Items.Clear()
lstProductSel.Items.Clear()
lstProduct.Enabled = True
g_strSQL = String.Empty
objcmd.Connection = ControlConnection
'Clear location combo box
Select Case intProduct
Case Product.Summary
g_strSQL = g_strSQL & "pc_mis_busunit_product_relate_summary "
Case Product.Detail
g_strSQL = "SELECT DISTINCT b.dtl_prod_cd, rtrim(ltrim(b.dtl_prod_desc))"
g_strSQL = g_strSQL & " FROM product_detail_ref b "
g_strSQL = g_strSQL & " ORDER BY rtrim(ltrim(b.dtl_prod_desc)) "
Case Else
Exit Sub
End Select
If p_and_C <> String.Empty Then
g_strSQL = g_strSQL & "'" & String.Empty & "','" & String.Empty & "','" & p_and_C & "'"
End If
If g_strSQL <> "" Then
objcmd.CommandText = g_strSQL
rsProducts = objcmd.ExecuteReader()
End If
'Process results from query
If rsProducts.HasRows = False Then
rsProducts.Close()
Exit Sub
Else
' This nested if will check which radio button is selected and add the corresponding
' 'all' entry to the top of the lstProduct box
If rdbProductPC.Checked = True Then
ProductList.Items.Add(PAndCConstants.ALL_P_AND_C)
ElseIf rdbProductNonPC.Checked = True Then
ProductList.Items.Add(PAndCConstants.ALL_NON_P_AND_C)
Else
ProductList.Items.Add(PAndCConstants.ALL)
End If
ProductList.SelectedIndex = 0
While rsProducts.Read()
ProductList.Items.Add(rsProducts(0))
End While
ProductList.SetSelected(0, True)
rsProducts.Close()
End If
rsProducts = Nothing
End Sub