LogIn form with user and admin using VB.net and Mysql - vb.net

I want to get the privilege if it's admin or encoder but with this code I can't get any value... this is my code please help me
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
cn = New MySqlConnection
cn.ConnectionString = "server=localhost; userid=root; database=dp_inventory;"
Dim reader As MySqlDataReader
Try
cn.Open()
Dim sql As String
sql = "Select from dp_inventory.user_account where employeeID='" & UsernameTextBox.Text & "' and password='" & PasswordTextBox.Text & "' "
cmd = New MySqlCommand(sql, cn)
reader = cmd.ExecuteReader
Dim count As Integer
count = 0
While reader.Read
count = count + 1
End While
Dim users As String
users = "select privilege from user_account where employeeID='" & UsernameTextBox.Text & "'"
If count = 1 Then
If users = "admin" Then
frmAdminMain.Show()
ElseIf users = "encoder" Then
MainForm.Show()
End If
ElseIf count > 1 Then
frmAdminMain.Show()
Else
MsgBox("tryy again")
End If
Catch ex As Exception
MsgBox("Try again")
End Try
End Sub

There are quite a few errors in this code you wrote. Your first issue is you are simply trying to count without actually using a Sql counter.
Take a look at a code snippet from one of my applications here for a general idea
SelectStr = "SELECT MagPieces_Number,MagOperators_Number,MagFactor_Number,MagTotal_Number" & _
" FROM Parts_Mag WHERE Quote_Number_Id = #QuoteId and Quote_Rev_Id = #RevId and Part_Number_Id = #PartID and Part_Numeral_Id = #PartNumeral and SiteLocation = #Site"
SqlDataCmd = New SqlCommand(SelectStr, SqlConn)
SqlDataCmd.Parameters.AddWithValue("#QuoteId", QuoteId)
SqlDataCmd.Parameters.AddWithValue("#RevId", RevId)
SqlDataCmd.Parameters.AddWithValue("#PartId", PartNumber)
SqlDataCmd.Parameters.AddWithValue("#PartNumeral", PartNumeral)
SqlDataCmd.Parameters.AddWithValue("#Site", SiteLocation)
SqlReader = SqlDataCmd.ExecuteReader
While SqlReader.Read
MagPieces = SqlReader("MagPieces_Number").ToString
MagOperators = SqlReader("MagOperators_Number").ToString
MagFactor = SqlReader("MagFactor_Number").ToString
MagTotal = SqlReader("MagTotal_Number").ToString
End While
MagParticle.txtPiecesPerHour.Text = MagPieces
MagParticle.txtOperators.Text = MagOperators
MagParticle.txtMatFactor.Text = MagFactor
MagParticle.labMagTotal.Text = MagTotal
Catch ex As Exception
ErrorMessage(ex.message)
SqlReader.Close()
End Try
SqlReader.Close()
If you are simply looking for if your select statement has "Admin" or "Encoder" at the end, it would simply be something like this:
Dim empId as String = UsernameTextbox.Text
Dim SelectStr as String = "Select privilege from dp_inventory.user_account where employeeID=#empId
SqlDataCmd = New SqlCommand(SelectStr, SqlConn)
SqlDataCmd.Parameters.AddWithValue("#empId", empId)
Then read it with a reader. Once you have the general idea you should be able to take it from there! Im not quite sure why you need the count to begin with so you may want to just negate that portion out and simply read from your table based on the ID

Related

Availability using Access Database

I am attempting to make a hotel booking system. However the availability has got me a bit confused. I have about 15 buttons which I am able to save the number to the database but when the form loads/ date changed. I need the button to stay red and be unclickable. For example if I had a room 11 booked from 3/06/17 to 5/06/17 then I'd need the button to remain red from the 3/06/17 to 4/06/17 since the room is able to still be booked on the 5/06/17 after cleaning. I hope this makes sense. Below is the code I am using to try to do this. The code does run however the button does not turn red.
I was thinking does my SQL statement need to be changed but I'm not too sure. I'm pretty new to coding so an explanation would be helpful. Thanks.
Private Sub ReadRecords()
Dim btn As Button = Nothing
Dim BookingFound As Boolean = False
Using MyConn As New OleDbConnection
MyConn.ConnectionString = connString
MyConn.Open()
Dim check As String = "SELECT COUNT(*) FROM [BookingInformation] WHERE [Date In] = '" & dtpDateIn.Value.Date & "' AND [Date Out] = '" & dtpDateOut.Value.Date & "'"
Dim BookingExists As Boolean = False
Dim command As OleDbCommand = New OleDbCommand(check, MyConn)
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
If reader(0) = 0 Then
BookingExists = False
Else
BookingExists = True
End If
End While
End Using
If BookingExists = True Then
Dim getData As String = "SELECT * FROM [BookingInformation] WHERE [Date Out] = '" & dtpDateOut.Text & "'"
Dim command2 As OleDbCommand = New OleDbCommand(getData, MyConn)
Using reader As OleDbDataReader = command2.ExecuteReader()
While reader.Read()
BookingFound = True
strDateIn = reader("Date In").ToString()
strDateOut = reader("DateOut").ToString
strRoomNumber = reader("Room Number").ToString
End While
If BookingFound = True Then
btn.BackColor = Color.Red
End If
End Using
End If
MyConn.Close()
End Using
End Sub
Private Sub Room_Booking_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ReadRecords()
End Sub
You should make your access database understand your input as date, access database is very sensitive to datatypes, for example if you write
"SELECT * FROM [user_tb] WHERE user_id=1"
Your code will work fine if your user_id data type is autonumber.
so try
Dim getData As String = "SELECT * FROM [BookingInformation] WHERE [Date Out] = #" & dtpDateOut.Text & "#"
Instead of
Dim getData As String = "SELECT * FROM [BookingInformation] WHERE [Date Out] = '" & dtpDateOut.Text & "'"
That is replace ' with #

Use VB.NET Manipulate Microsoft Access Database

How can I make this work?
Private Sub ListView_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView.MouseClick
conndb = New OleDbConnection
conndb.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database1.accdb"
Try
conndb.Open()
Dim str As String
str = "Select * FROM customer WHERE CustomerID = '" & ListView.FocusedItem.Text & "'"
COMMAND = New OleDbCommand(str, conndb)
dr = COMMAND.ExecuteReader
If dr.Read = True Then
txtID.Text = dr("CustomerID")
txtFirstName.Text = dr("FirstName")
txtSurname.Text = dr("Surname")
txtAddress.Text = dr("Address")
txtCN1.Text = dr("ContactNo1")
txtCN2.Text = dr("ContactNo2")
txtEmail.Text = dr("EmailAddress")
txtRemarks.Text = dr("Remarks")
txtDebtStatus.Text = dr("DebtStatus")
txtDownPay.Text = dr("DownPayment")
txtDebtBal.Text = dr("DebtBal")
txtCustomerDate.Text = dr("Date")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conndb.Dispose()
End Try
End Sub
I need help on how can I make this run without errors, Im using ms access as my database source. There seems to be an error using this code, this code works perfectly fine with mysql but in ms access, it says data mistype error or something like that. Need your help, thanks
Remove the ' surrounding the field CustomerID in your query :
str = "Select * FROM customer WHERE CustomerID = '" & ListView.FocusedItem.Text & "'"
becomes :
str = "Select * FROM customer WHERE CustomerID = " & ListView.FocusedItem.Text
MS Access sees a string when you put an apostrophe, so there is a Type Mismatch Exception, because it is expecting a number...
However, this is a pretty bad idea as Parametrized queries are a better way of doing this (see : Why should I create Parametrized Queries ?)
Also, Use Using
So all in all, it's just another brick in the wall :
Private Sub ListView_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView.MouseClick
Using conndb As New OleDbConnection
conndb.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database1.accdb"
Try
conndb.Open()
Dim str As String
str = "Select * FROM customer WHERE CustomerID = #Customer"
Using COMMAND As New OleDbCommand(str, conndb)
COMMAND.Parameters.Add("#Customer", SqlDbType.Integer).Value = Integer.Parse(ListView.FocusedItem.Text)
dr = COMMAND.ExecuteReader
If dr.Read = True Then
txtID.Text = dr("CustomerID")
txtFirstName.Text = dr("FirstName")
txtSurname.Text = dr("Surname")
txtAddress.Text = dr("Address")
txtCN1.Text = dr("ContactNo1")
txtCN2.Text = dr("ContactNo2")
txtEmail.Text = dr("EmailAddress")
txtRemarks.Text = dr("Remarks")
txtDebtStatus.Text = dr("DebtStatus")
txtDownPay.Text = dr("DownPayment")
txtDebtBal.Text = dr("DebtBal")
txtCustomerDate.Text = dr("Date")
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
Take a look at this sample code that I put together a while back. You can probably learn a lot from this.
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged, TextBox1.Click
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\your_path\Desktop\Northwind_2012.mdb"
Dim selectCommand As String
Dim connection As New OleDbConnection(connectionString)
'selectCommand = "Select * From MyExcelTable where Fname = '" & TextBox1.Text & "'"
'"SELECT * FROM Customers WHERE Address LIKE '" & strAddressSearch & "%'"
'or ending with:
'"SELECT * FROM Customers WHERE Address LIKE '%" & strAddressSearch & "'"
selectCommand = "Select * From MyExcelTable where Fname Like '" & TextBox1.Text & "%'"
Me.dataAdapter = New OleDbDataAdapter(selectCommand, connection)
With DataGridView1
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
End With
Dim commandBuilder As New OleDbCommandBuilder(Me.dataAdapter)
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
Me.bindingSource1.DataSource = table
Dim data As New DataSet()
data.Locale = System.Globalization.CultureInfo.InvariantCulture
DataGridView1.DataSource = Me.bindingSource1
Me.DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua
Me.DataGridView1.AutoResizeColumns( _
DataGridViewAutoSizeColumnsMode.AllCells)
End Sub

Visual basic - Incrementing the score

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim READER As MySqlDataReader
Dim Query As String
Dim connection As MySqlConnection
Dim COMMAND As MySqlCommand
Dim item As Object
Try
item = InputBox("What is the item?", "InputBox Test", "Type the item here.")
If item = "shoe" Then
Dim connStr As String = ""
Dim connection As New MySqlConnection(connStr)
connection.Open()
Query = "select * from table where username= '" & Login.txtusername.Text & " '"
COMMAND = New MySqlCommand(Query, connection)
READER = COMMAND.ExecuteReader
If (READER.Read() = True) Then
Query = "UPDATE table set noOfItems = noOfItems+1, week1 = 'found' where username= '" & Login.txtusername.Text & "'"
Dim noOfItems As Integer
Dim username As String
noOfItems = READER("noOfItems") + 1
username = READER("username")
MessageBox.Show(username & "- The number of items you now have is: " & noOfGeocaches)
End If
Else
MsgBox("Unlucky, Incorrect item. Please see hints. Your score still remains the same")
End If
Catch ex As Exception
MessageBox.Show("Error")
End Try
I finally got the message box to display! but now my code does not increment in the database, can anybody help me please :D
Thanks in advance
After fixing your typos (space after the login textbox and name of the field retrieved) you are still missing to execute the sql text that updates the database.
Your code could be simplified understanding that an UPDATE query has no effect if the WHERE condition doesn't find anything to update. Moreover keeping an MySqlDataReader open while you try to execute a MySqlCommand will trigger an error in MySql NET connector. (Not possible to use a connection in use by a datareader). We could try to execute both statements in a single call to ExecuteReader separating each command with a semicolon and, of course, using a parameter and not a string concatenation
' Prepare the string for both commands to execute
Query = "UPDATE table set noOfItems = noOfItems+1, " & _
"week1 = 'found' where username= #name; " & _
"SELECT noOfItems FROM table WHERE username = #name"
' You already know the username, don't you?
Dim username = Login.txtusername.Text
' Create the connection and the command inside a using block to
' facilitate closing and disposing of these objects.. exceptions included
Using connection = New MySqlConnection(connStr)
Using COMMAND = New MySqlCommand(Query, connection)
connection.Open()
' Set the parameter value required by both commands.
COMMAND.Parameters.Add("#name", MySqlDbType.VarChar).Value = username
' Again create the reader in a using block
Using READER = COMMAND.ExecuteReader
If READER.Read() Then
Dim noOfItems As Integer
noOfItems = READER("noOfItems")
MessageBox.Show(username & "- The number of items you now have is: " & noOfItems )
End If
End Using
End Using
End Using

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

How to return multiple values from a query vb.net

one question how to store or return multiple queries result values into multiple variables.. I'm using a query that return 4 columns but how to.. individual store those results into 4 separate variables.. here is my code
Private Sub FrmAlumnos_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
txtCurrentUser.Text = Login.txtUser.Text
Dim strsql As String
strsql = "SELECT ""Agregar"", ""Modificar"", ""Eliminar"", ""Imprimir"" FROM ""Seguridad"".""GrupoPantallas"" WHERE ""IdGrupo"" = (SELECT ""IdGrupo"" FROM ""Seguridad"".""Users"" WHERE ""IdUsers"" = '" _
+ Me.txtCurrentUser.Text + "') AND ""IdPantalla"" = '" + Me.Name + "'"
Try
Using conexion As New Devart.Data.PostgreSql.PgSqlConnection(My.Settings.CNX_Principal)
Dim comando As New Devart.Data.PostgreSql.PgSqlCommand(strsql, conexion)
conexion.Open()
Dim registro As Devart.Data.PostgreSql.PgSqlDataReader = comando.ExecuteReader
If comando.ExecuteReader.Item(0) = 0 Then
btnNew.Visible = False
End If
If comando.ExecuteReader.Item(1) = 0 Then
btnEdit.Visible = False
End If
If comando.ExecuteReader.Item(2) = 0 Then
btnDelete.Visible = False
End If
If comando.ExecuteReader.Item(3) = 0 Then
btnPrint.Visible = False
End If
End Using
Catch ex As Exception
End Try
End Sub
I'm Using PostgreSQL just for you to know...
I think you might find a DataSet to be useful here. Something like:
Dim ds As New DataSet
Dim com As New SqlCommand
com.Connection = <yourconnectionstring>
com.CommandType = CommandType.Text
com.CommandText = "YOURSQLSTUFF"
Dim da As New DataAdapter
da.SelectCommand = com
da.Fill(ds)
ds.Tables(0).TableName = "FirstTable"
ds.Tables(0).PrimaryKey = New DataColumn() {ds.Tables(0).Columns("primaryKeyOfFirstTable")
ds.Tables(1).TableName = "SecondTable"
ds.Tables(1).PrimaryKey = New DataColumn() {ds.Tables(1).Columns("primaryKeyOfSecondTable")
Hope that helps!
-sf
EDIT: After some more searching, I found this link, which might help you out! It's postgreSQL specific!
You need to use the Read method of the DataReader:
Dim strsql As String
strsql = "SELECT ""Agregar"", ""Modificar"", ""Eliminar"", ""Imprimir"" FROM ""Seguridad"".""GrupoPantallas"" WHERE ""IdGrupo"" = (SELECT ""IdGrupo"" FROM ""Seguridad"".""Users"" WHERE ""IdUsers"" = '" _
+ Me.txtCurrentUser.Text + "') AND ""IdPantalla"" = '" + Me.Name + "'"
Try
Using conexion As New Devart.Data.PostgreSql.PgSqlConnection(My.Settings.CNX_Principal)
Dim comando As New Devart.Data.PostgreSql.PgSqlCommand(strsql, conexion)
conexion.Open()
Using registro As Devart.Data.PostgreSql.PgSqlDataReader = comando.ExecuteReader()
//Assuming that there is only a single row returned
If registro.Read()
btnNew.Visible = registro.GetBoolean(0)
btnEdit.Visible = registro.GetBoolean(1)
btnDelete.Visible = registro.GetBoolean(2)
btnPrint.Visible = registro.GetBoolean(3)
End While
End Using
End Using
Catch ex As Exception
End Try
You should also look into using parameters. It would make the code a little cleaner than using a concatenated string and would stop sql injection attacks.
Dim strsql As String
strsql = "SELECT ""Agregar"", ""Modificar"", ""Eliminar"", ""Imprimir"" FROM ""Seguridad"".""GrupoPantallas"" WHERE ""IdGrupo"" = (SELECT ""IdGrupo"" FROM ""Seguridad"".""Users"" WHERE ""IdUsers"" = '" _
+ Me.txtCurrentUser.Text + "') AND ""IdPantalla"" = '" + Me.Name + "'"
Try
Using conexion As New Devart.Data.PostgreSql.PgSqlConnection(My.Settings.CNX_Principal)
Dim comando As New Devart.Data.PostgreSql.PgSqlCommand(strsql, conexion)
conexion.Open()
Dim registro As Devart.Data.PostgreSql.PgSqlDataReader = comando.ExecuteReader
//This is the loop that you missed
While registro.Read()
If comando.ExecuteReader.Item(0) = 0 Then
btnNew.Visible = False
End If
If comando.ExecuteReader.Item(1) = 0 Then
btnEdit.Visible = False
End If
If comando.ExecuteReader.Item(2) = 0 Then
btnDelete.Visible = False
End If
If comando.ExecuteReader.Item(3) = 0 Then
btnPrint.Visible = False
End If
End While
End Using
Catch ex As Exception
End Try
I'm not sure if this is what you're trying to do, but all you have to do is loop through the DataReader as shown above.