How do i change this code to VB.NET? So i want to use a DataSet instead of the ADODB.Recordset and an OleDb.OleDbConnection instead of ADODB.Connection.
Set oRs = New ADODB.Recordset
oRs.Open ("Select * from Login Where Username= '" & txtUsername.Text & "'"),oCn, adOpenStatic, adLockOptimistic, _
adCmdText
If txtPassword.Text <> oRs.Fields("Password") Then
Call MsgBox("Incorrect Password", vbOKOnly, "Login Error")
txtPassword.Text = ""
txtPassword.SetFocus
Exit Sub
Else
strUserName = txtUsername.Text 'May need in the future project
strName = oRs.Fields("FirstName") & " " & oRs.Fields("LastName")
frmInstruction.Show
This is what I have tried so far:
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM Login WHERE Username= '" & txtUsername.Text & "' AND password = '" & txtPassword.Text & "' ", oCn)
Dim sdr As OleDbDataReader = cmd.ExecuteReader()
If (sdr.Read() = True) Then
strUserName = txtUsername.Text
frmInstruction.Show()
'but am having issue with this line of code:
strName = oRs.Fields("FirstName") & " " & oRs.Fields("LastName")
'but am having issue with this line of code: strName =
oRs.Fields("FirstName") & " " & oRs.Fields("LastName")
You could use OledbDataReader.GetString to read the FirstName and LastName fields:
Dim firstName = sdr.GetString(sdr.GetOrdinal("FirstName"))
Dim lastName = sdr.GetString(sdr.GetOrdinal("LastName"))
strName = firstName & " " & lastName
Related
Imports System.Data.OleDb
Imports System.Data
Public Class Form3
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ran As New Random
TextBox2.Text = ran.Next(1, 8)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" Or MaskedTextBox3.Text = "" Then
MsgBox("Please fill all text boxes With the required info")
Else
Dim cmd As OleDbCommand
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source =C:\users\nikh8610\Documents\users.accdb")
Dim str As String
con.Open()
str = "UPDATE users SET username = '" & TextBox1.Text & "'WHERE (ID = '" & TextBox2.Text & "') AND password='" & MaskedTextBox3.Text & "' WHERE (ID = '" & TextBox2.Text & "')"
cmd = New OleDbCommand(str, con)
cmd.ExecuteNonQuery()
con.Close()
End If
End Sub
End Class
Your query isn't valid. You are using two WHERE parts on the query. Try the following:
str = "UPDATE users SET username = '" & TextBox1.Text & "' WHERE ID = '" & TextBox2.Text & "' AND password='" & MaskedTextBox3.Text & "'"
You also don't UPDATE the password of the user. You can use something like the following to UPDATE the username and password.
str = "UPDATE users SET username = '" & txtUsername.Text & "', password = '" & txtNewPassword.Text & "' WHERE ID = '" & txtUserID.Text & "' AND password = '" & txtOldPassword.Text & "'"
You should also use prepared statements to UPDATE the user information:
Dim cmd As OleDbCommand = New OleDbCommand()
cmd.Connection = con
cmd.CommandText = "UPDATE users SET username = ?, password = ? WHERE ID = ? AND password = ?"
cmd.Parameters.Add("NewUsername", OleDbType.VarWChar, 50)
cmd.Parameters.Add("NewPassword", OleDbType.VarWChar, 50)
cmd.Parameters.Add("UserID", OleDbType.Long)
cmd.Parameters.Add("OldPassword", OleDbType.VarWChar, 50)
cmd.Parameters(0).Value = txtNewUsername.Text
cmd.Parameters(1).Value = txtNewPassword.Text
cmd.Parameters(2).Value = txtUserID.Text
cmd.Parameters(3).Value = txtOldPassword.Text
cmd.Prepare()
cmd.ExecuteNonQuery()
I'm attempting to input a variable declared as a string into my access database. When the button is clicked "Ticket Status" is not entered into the access database.
Dim str As String
str = "update [tblUsers] set [Campus] = '" & cmboxCampus.SelectedItem & "' , [ProblemType] = '" & cmboxProblemType.SelectedItem & "', [IfOther] = '" & txtIfOther.Text & "', [Status] = '" & TicketStatus & "', [ProblemDescription] = '" & txtDescription.Text & "' Where [Username] = '" & txtUsername.Text & "'"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
TicketStatus = "Ticket being Assigned"
If txtIfOther.ReadOnly = True And txtIfOther.Text <> "" Then
MsgBox("When selecting 'other' please specify")
End If
If txtDescription.Text = "" Or cmboxCampus.SelectedItem = "" Or cmboxProblemType.SelectedItem = "" Then
MsgBox("Please fill out all fields.", MsgBoxStyle.Information)
Else
Try
cmd.ExecuteNonQuery()
cmd.dispose()
myConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
MsgBox("Your ticket has been successfully submitted.", MsgBoxStyle.Information)
End If
End Sub
My INSERT statement apparently has a syntax error. Could someone please explain why that might be?
Private Sub Register_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Register.Click
Dim StudentNum As String
Dim Password As String
Dim FirstName As String
Dim LastName As String
Dim YrandSec As String
StudentNum = Number.Text()
Password = Pass.Text
FirstName = First.Text
LastName = Last.Text
YrandSec = YrSec.Text()
SQL = "INSERT INTO Accounts(StudNo,Password,FirstName,LastName,YrandSec) VALUES ('" & StudentNum & "', '" & Password & "', '" & FirstName & "', '" & LastName & "', '" & YrandSec & "')" - ERROR HERE
Cmd = New OleDbCommand(SQL, Con)
Con.Open()
objCmd = New OleDbCommand(SQL, Con)
If Repass.Text = Pass.Text = False Then
Re.Text = "*Password didn't match!"
Number.Text = ""
Pass.Text = ""
Repass.Text = ""
Con.Close()
Else
If Number.Text = "" Or Pass.Text = "" Or Repass.Text = "" Or First.Text = "" Or Last.Text = "" Or YrSec.Text = "" Then
MsgBox("Please complete the field", MsgBoxStyle.Information, "Failed to create")
Else
objCmd.ExecuteNonQuery()
Re.Text = ""
MsgBox("Account has been created", MsgBoxStyle.Information, "Congrats!")
For fade = 0.0 To 1.1 Step 0.2
Login.Opacity = fade
Login.Show()
Me.Hide()
Threading.Thread.Sleep(30)
Number.Text = ""
Pass.Text = ""
Repass.Text = ""
First.Text = ""
Last.Text = ""
YrSec.Text = ""
Next
End If
End If
End Sub
PASSWORD is a reserved word in Access SQL, so you need to wrap that column name in square brackets.
You really should use a parameterized query to protect against SQL Injection and generally make your life easier.
Try something like this
SQL = "INSERT INTO [Accounts] ([StudNo],[Password],[FirstName],[LastName],[YrandSec]) " & _
"VALUES (?, ?, ?, ?, ?)"
Con.Open()
objCmd = New OleDbCommand(SQL, Con)
objCmd.Parameters.AddWithValue("?", StudentNum)
objCmd.Parameters.AddWithValue("?", Password)
objCmd.Parameters.AddWithValue("?", FirstName)
objCmd.Parameters.AddWithValue("?", LastName)
objCmd.Parameters.AddWithValue("?", YrandSec)
remove those double quotes inside your sql statement.
I asked a question previously concerning updating data in a datagridview with phpMyAdmin. You can refer to it by following link -->Updating data in phpmyadmin part 1
The code works quite OK, but now the problem is that when I check for the updated data in localhost all I see are empty fields. Below is the screenshot of my vb in design. I have labelled the textboxes as per my database. The textboxes in the screenshot are set to be invisible on running my winform.
What exactly could be the problem?
#Kakarot
Here is what I initially had
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=server;password=server;database=heavisa_database"
Dim rabit As MySqlDataReader
MysqlConn.Open()
Dim pin As String
pin = "UPDATE heavisa_database.new_employee SET (Employee_ID = '" & txtemployeeid.Text & "', Nat_ID = '" & txtnatid.Text & "', First_Name = '" & txtfirstname.Text & "', Middle_Name = '" & txtmiddlename.Text & "', Surname = '" & txtsurname.Text & "', NSSF_No = '" & txtnssfno.Text & "', KRA_Pin = '" & txtkrapin.Text & "', NHIF_No = '" & txtnhifno.Text & "', Residence = '" & txtresidence.Text & "', Mobile_No = '" & txtmobileno.Text & "', Email = '" & txtemail.Text & "', Job_Group = '" & cbojobgroup.Text & "', Employment_Date = '" & dtpemploymentdate.Text & "') WHERE Employee_ID = '" & txtemployeeid1.Text & "'"
Try
con = New MySqlCommand(pin, MysqlConn)
rabit = con.ExecuteReader
MessageBox.Show("Update Successful.")
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
And here is what I currently have (credit goes to one Mr. ekad for it)
Dim pin As String
pin = "UPDATE heavisa_database.new_employee SET Employee_ID = #Employee_ID, Nat_ID = #Nat_ID, First_Name = #First_Name, Middle_Name = #Middle_Name, Surname = #Surname, NSSF_No = #NSSF_No, KRA_Pin = #KRA_Pin, NHIF_No = #NHIF_No, Residence = #Residence, Mobile_No = #Mobile_No, Email = #Email, Job_Group = #Job_Group, Employment_Date = #Employment_Date WHERE Employee_ID like '%{0}%'"
Try
Using MysqlConn As New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=server;password=server;database=heavisa_database"
MysqlConn.Open()
Using con As New MySqlCommand(pin, MysqlConn)
With con
con.Parameters.AddWithValue("#Employee_ID", txtemployeeid.Text)
con.Parameters.AddWithValue("#Nat_ID", txtnatid.Text)
con.Parameters.AddWithValue("#First_Name", txtfirstname.Text)
con.Parameters.AddWithValue("#Middle_Name", txtmiddlename.Text)
con.Parameters.AddWithValue("#Surname", txtsurname.Text)
con.Parameters.AddWithValue("#NSSF_No", txtnssfno.Text)
con.Parameters.AddWithValue("#KRA_Pin", txtkrapin.Text)
con.Parameters.AddWithValue("#NHIF_No", txtnhifno.Text)
con.Parameters.AddWithValue("#Residence", txtresidence.Text)
con.Parameters.AddWithValue("#Mobile_No", txtmobileno.Text)
con.Parameters.AddWithValue("#Email", txtemail.Text)
con.Parameters.AddWithValue("#Job_Group", cbojobgroup.Text)
con.Parameters.AddWithValue("#Employment_Date", dtpemploymentdate.Text)
End With
con.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("Update Successful.")
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
The first code gave me an error (refer to the link above). The second code works but it's emptying my fields instead of updating.
How did you updated your tables in your database? It should be like:
(Im gonna take my code for an old project that I did)
Private Sub disconnect()
conn.Close()
End Sub
Private Sub connect()
conn.ConnectionString = connectionString
conn.Open()
End Sub
Private Sub btnSaveEdit_Click(sender As Object, e As EventArgs) Handles btnSaveEdit.Click
connect()
Dim query as string
Dim command As New MySqlCommand
query = "Update `tblcandidates` set firstname = '" & txtEditFname.Text & "', lastname = '" & txtEditLName.Text & "', position='" & cboEditPosition.Text & "', fullname = '" & fullname & "' where recNum = '" & txtRec.Text & "'"
command.Connection = conn
command.CommandText = query
command.ExecuteNonQuery()
disconnect()
End Sub
First things first, just a simple question, is heavisa_database.new_employee a table? It's really wise to properly name them, you can put tbl before your desired name if its a table, and db before the name if its a database. Just to prevents confusions. And I think you dont need a reader when updating records in your table, correct me if I'm wrong :p
Okay, to be honest, I don't really understand much the code that Mr. ekad provided. Here's a code you can try. And oh, you don't really need the bracket after the SET.
//Global Vars
Dim connectionString As String = "server=localhost;userid=server;password=server;database=heavisa_database"
Dim conn As New MySqlConnection
First, let's make some functions for ease (you can put this anywhere in your code):
//remember that conn is our MySqlConnection
Private Sub connect()
conn.ConnectionString = connectionString
conn.Open()
End Sub
Private Sub disconnect()
conn.Close()
End Sub
So, event for your update button:
connect()
Dim pin As String
pin = "UPDATE new_employee SET Employee_ID = '" & txtemployeeid.Text & "', Nat_ID = '" & txtnatid.Text & "', First_Name = '" & txtfirstname.Text & "', Middle_Name = '" & txtmiddlename.Text & "', Surname = '" & txtsurname.Text & "', NSSF_No = '" & txtnssfno.Text & "', KRA_Pin = '" & txtkrapin.Text & "', NHIF_No = '" & txtnhifno.Text & "', Residence = '" & txtresidence.Text & "', Mobile_No = '" & txtmobileno.Text & "', Email = '" & txtemail.Text & "', Job_Group = '" & cbojobgroup.Text & "', Employment_Date = '" & dtpemploymentdate.Text & "' WHERE Employee_ID = '" & txtemployeeid1.Text & "'"
//lets create new command
Dim command As New MySqlCommand
//sets the connection for our command
command.Connection = conn
command.CommandText = pin
command.ExecuteNonQuery()
disconnect()
MessageBox.Show("Record saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
Try the given code above and I'm pretty sure It'll work. Goodluck!
I cant figure out whats wrong with this,when i update a record from my list view a pop up appears saying no value given for one or more required parameters.
heres my code:
Private Sub BtnUpdate_Click(sender As Object, e As EventArgs) Handles BtnUpdate.Click
Try
Dim SqlQuery As String = "UPDATE UsersTable Set AccountType = '" & CmbAccountType.Text & "' , Username = '" & TxtUsername.Text & "' , UserPassword = '" & TxtPassword.Text & "' , Firstname = '" & TxtFirstname.Text & "' , Lastname = '" & TxtLastname.Text & "' , Sex = '" & CmbSex.Text & "',Birthdate = '" & DateTimePickerBirthdate.Text & "' , ContactNumber = '" & TxtContact.Text & "' , Address = '" & TxtAddress.Text & "' WHERE UserID = " & id & ";"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = Conn
.ExecuteNonQuery()
End With
MsgBox("Account successfully updated!")
loadlistview()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub BtnDelete_Click(sender As Object, e As EventArgs) Handles BtnDelete.Click
Try
Dim SqlQuery As String = "DELETE FROM ProductTable WHERE UserID = " & id & ";"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = Conn
.ExecuteNonQuery()
End With
MsgBox("Account deleted.")
loadlistview()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
The problem is in the WHERE condition which you used in your query. so you can correct it by using the following query
In update query :
Dim SqlQuery As String = "UPDATE UsersTable Set AccountType = '" & CmbAccountType.Text & "'....................." & _
"WHERE UserID = '" & id & "';" '<----- you miss a single quote in where clause.
In Delete query :
Dim SqlQuery As String = "DELETE FROM ProductTable WHERE UserID = '" & id & "';"