vb.net call the same function twice from button Event Click - vb.net

This is my code on button event click function
Dim con As New Koneksi
DataGridView1.Rows.Add(con.getIdTambahBarang(cbBarang.Text), _
con.getNamaTambahBarang(cbBarang.Text), _
con.getHargaTambahBarang(cbBarang.Text), _
txtJumlah.Text)
This is my class Koneksi code :
Public Function getIdNamaHargaTambahBarang(ByVal namaBarang As String, ByVal params As String) As String
Dim id As String = ""
Dim nama As String = ""
Dim harga As String = ""
Try
bukaKoneksi()
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT * FROM barang WHERE nama_barang like '" & namaBarang & "'"
reader = cmd.ExecuteReader
If (reader.Read()) Then
If params = "getNama" Then
nama = reader.GetString(1)
Return nama
End If
If params = "getHarga" Then
harga = reader.GetDouble(2).ToString
Return harga
End If
If params = "getId" Then
id = reader.GetString(0)
Return id
End If
End If
tutupKoneksi()
Catch ex As Exception
End Try
End Function
Public Function getIdTambahBarang(ByVal namaBarang As String) As String
Return getIdNamaHargaTambahBarang(namaBarang, "getId")
End Function
Public Function getNamaTambahBarang(ByVal namaBarang As String) As String
Return getIdNamaHargaTambahBarang(namaBarang, "getNama")
End Function
Public Function getHargaTambahBarang(ByVal namaBarang As String) As String
Return getIdNamaHargaTambahBarang(namaBarang, "getHarga")
End Function
Both of the code above, produces
'System.InvalidOperationException' occurred in System.Data.dll error.
When I debug it, the second call of con produces this error. It seems that in VB.NET, the instance class function only can called once at a time, any solution?

Consider refactoring your code. You're actually hitting the database 3 times, each with a LIKE clause, where you really only need to do this once.
Suggest something like this, which performs the same business logic that you've got, with only one call to your database. It's also got some SQL injection prevention.
Dim con As New Koneksi
Dim barang As Barang = Koneksi.GetBarang()
DataGridView1.Rows.Add(barang.id,
barang.nama, _
barang.harga, _
txtJumlah.Text)
Public Class Koneksi
Public Function GetBarang(nama_barang As String)
Dim barang As New Barang
bukaKoneksi()
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT id,name,harga FROM barang WHERE nama_barang = #nama"
cmd.Parameters.AddWithValue("#nama", namaBarang)
reader = cmd.ExecuteReader
If (reader.Read()) Then
barang.id = reader.reader.GetString(0)
barang.nama = reader.GetString(1)
barang.harga = reader.GetDouble(2).ToString
End If
tutupKoneksi()
Return barang
End Function
End Class
You'll retrieve your barang object properties in one statement. All three properties are gathered from the DB at once. When you inevitably want to add another property to your DataGridView, you won't have to make any extra round-trips to your database, but rather only modify your SQL statement, and the .Rows.Add) call.
The database is now safe from SQL injection in this call.
the code is easier to read and understand for the next developer coming into read this code.
the database was previously using more resources due to being called 3x, and using a LIKE clause, where you really only needed an = name.

Related

Insert data from VB net into Postgresql

I'm trying to input data from my vb into PostgreSQL
the source is another database on Ms Access
im using this code for connection
Public Function LoadAcces_tblpibconr() As DataTable 'ganti ini sesuai nama table
Dim Table As DataTable = New DataTable()
Command.Connection = conn.OpenConnection()
Command.CommandText = "select * from tblpibconr"
Command.CommandType = CommandType.Text
ReadRows = Command.ExecuteReader()
Table.Load(ReadRows)
ReadRows.Close()
conn.CloseConexion()
Return Table
End Function
'=====================================TABLE POSTGRESQL========================='
Public Function LoadNpgsql_tblpibconr() As DataTable
Dim Table As DataTable = New DataTable()
Cmd.Connection = connNpgsql.OpenConnection()
Cmd.CommandText = "select * from tblpibconr"
Cmd.CommandType = CommandType.Text
ReadRows1 = Cmd.ExecuteReader()
Table.Load(ReadRows1)
ReadRows1.Close()
connNpgsql.CloseConexion()
Return Table
End Function
I'm using this function for filtering the data
I'll compare the data first and take the data without a match and stored it into postgresql
Public Function CekData_tblpibconr(ByVal car As String, ByVal reskd As String, ByVal contno As String) As Boolean
Dim Table As DataTable = New DataTable()
Cmd.Connection = connNpgsql.OpenConnection()
If Cmd.Parameters.Count > 0 Then
Cmd.Parameters.Clear()
End If
Cmd.Parameters.AddWithValue("#car", car)
Cmd.Parameters.AddWithValue("#reskd", reskd)
Cmd.Parameters.AddWithValue("#contno", contno)
Cmd.CommandText = <sql>select * from tblpibconr where car=#car and reskd=#reskd and contno=#contno</sql>.Value
Cmd.CommandType = CommandType.Text
ReadRows1 = Cmd.ExecuteReader() 'ERROR System.InvalidOperationException: 'Parameter '#car' must have its value set'
Table.Load(ReadRows1)
ReadRows1.Close()
If Table.Rows.Count > 0 Then
Return False
Else
Return True
End If
Cmd.Parameters.Clear()
connNpgsql.CloseConexion()
End Function
Sub bandingkan_data_tblpibconr()
For i = 0 To DGV1.Rows.Count - 1
Dim validasi = query.CekData_tblpibconr(DGV1.Rows(i).Cells(0).Value, DGV1.Rows(i).Cells(1).Value, DGV1.Rows(i).Cells(2).Value) 'cek data dari access ke postgresql
If validasi = True Then 'jika data di access tidaj ada
'inser data
Dim a As String
If IsDBNull(DGV1.Rows(i).Cells(4).Value.ToString()) Then
a = "0"
Else
a = DGV1.Rows(i).Cells(4).Value.ToString()
End If
DGV1.Rows(i).DefaultCellStyle.BackColor = Color.MistyRose
Dim Insertdata = query.insertNpgsql_tblpibconr(DGV1.Rows(i).Cells(0).Value.ToString(), DGV1.Rows(i).Cells(1).Value.ToString(), DGV1.Rows(i).Cells(2).Value.ToString() _
, DGV1.Rows(i).Cells(3).Value.ToString(), a)
If Insertdata = True Then
' MsgBox("Masuk")
Else
MsgBox("Data Gagal DIMASUKAN")
End If
End If
Next i
LoadNpgsql_tblpibconr()
MsgBox("Selesai")
End Sub
Public Function insertNpgsql_tblpibconr(ByVal car As String, ByVal reskd As String, ByVal contno As String, ByVal contukur As String, ByVal conttipe As String) As Boolean
Cmd.Connection = connNpgsql.OpenConnection()
If Cmd.Parameters.Count = 0 Then
Cmd.Parameters.Clear()
End If
Try
Cmd.CommandText = "insert into tblpibconr(car,reskd,contno,contukur,conttipe) values(#car,#reskd,#contno,#contukur,#conttipe)"
Cmd.CommandType = CommandType.Text
Cmd.Parameters.AddWithValue("#car", car)
Cmd.Parameters.AddWithValue("#reskd", reskd)
Cmd.Parameters.AddWithValue("#contno", contno)
Cmd.Parameters.AddWithValue("#contukur", contukur)
Cmd.Parameters.AddWithValue("#conttipe", conttipe)
Cmd.ExecuteNonQuery()
str = "insert into tblpibconr(car,reskd,contno,contukur,conttipe) values(#car , #reskd , #contno, #contukur, #conttipe)"
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
connNpgsql.CloseConexion()
End Function
this is the error that I get
System.InvalidOperationException: 'Parameter '#car' must have its
value set'
ITS Refer to ReadRows1 = Cmd.ExecuteReader() on function cekdata_tblpibconr and Dim validasi = query.CekData_tblpibconr(DGV1.Rows(i).Cells(0).Value, DGV1.Rows(i).Cells(1).Value, DGV1.Rows(i).Cells(2).Value) on sub bandingkan_data_tblpibconr
but this error appear after the data successfully inserted to my Postgresql
Before running the Function where the error occurred, I have checked if we really have a value for car.
This method demonstrates what I mean by keeping your database objects local. The connection and command are created locally in a Using block. They will be closed and disposed even it there is an error.
You can pass the connection string directly to the constructor of the connection. Likewise, pass the command text and the connection to the constructor of the command. The default CommandType is CommandType.Text so it is not necessary to explicitly set that property.
Open the connection at the last possible moment directly before the command is executed.
Public Function CekData_tblpibconr(ByVal car As String, ByVal reskd As String, ByVal contno As String) As Boolean
If String.IsNullOrEmpty(car) Then
MessageBox.Show("Car has no value")
Return True '??
End If
Dim Table As DataTable = New DataTable()
Using cn As New NpgsqlConnection(ConStr),
cmd As New NpgsqlCommand("select * from tblpibconr where car=#car and reskd=#reskd and contno=#contno;", cn)
cmd.Parameters.Add("#car", NpgsqlDbType.Varchar).Value = car
cmd.Parameters.Add("#reskd", NpgsqlDbType.Varchar).Value = reskd
cmd.Parameters.Add("#contno", NpgsqlDbType.Varchar).Value = contno
cn.Open()
Table.Load(cmd.ExecuteReader)
End Using
If Table.Rows.Count > 0 Then
Return False
Else
Return True
End If
End Function

Database query not returning results from value

I am making a work management system and I am fairly new to Visual Basic.
What I am trying to do is retrieve the name of the employee from the database with the given ID. After that I want this name to be displayed in a Label. After that, he can press the Work Start or Work end buttons.
Here is the code:
Private Function employeeSearchwithID(PersonalNr As String) As String
Dim mitarbeiter As String
Dim r As DataRow
Access.ExecQuery("SELECT [Vorname], [Name] from [TA-Personal] WHERE ([Personal_Nr] = '" & PersonalNr & "');")
'Report and Abort on Erros or no Records found
If NoErros(True) = False Or Access.RecordCount < 1 Then Exit Function
r = Access.DBDT.Rows(0)
'Populate Label with Data
mitarbeiter = r.Item("Vorname") & " " & r.Item("Name")
Return mitarbeiter
End Function
It is used like this:
Private Sub tbxUserInput_KeyDown(sender As Object, e As KeyEventArgs) Handles tbxUserInput.KeyDown
If e.KeyCode = Keys.Enter Then 'employeeIDnumbersSelect()
Label5.Text = employeeSearchwithID(tbxUserInput.ToString)
End If
End Sub
So, the plan is to have this program running on a tablet connected to a scanner. Every employee will have a personal card. When they scan the card, I want their names to be displayed. Of course, the card will be with the ID. But I am having trouble with the names: when I give my personal number it comes up as an empty string.
I have a separate DB Module. I learned from a tutorial:
Imports System.Data.OleDb
Public Class DBControl
' DB Connection
Public DBCon As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\recycle2000.mdb;")
'DB Command
Public DBCmd As OleDbCommand
'DB Data
Public DBDA As OleDbDataAdapter
Public DBDT As DataTable
'Public Myreader As OleDbDataReader = DBCmd.ExecuteReader
'Query Paramaters
Public Params As New List(Of OleDbParameter)
' Query Stats
Public RecordCount As Integer
Public Exception As String
Public Sub ExecQuery(Query As String)
'Reset Query Stats
RecordCount = 0
Exception = ""
Try
'Open a connection
DBCon.Open()
'Create DB Command
DBCmd = New OleDbCommand(Query, DBCon)
' Load params into DB Command
Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
' Clear params list
Params.Clear()
' Execute command & fill Datatable
DBDT = New DataTable
DBDA = New OleDbDataAdapter(DBCmd)
RecordCount = DBDA.Fill(DBDT)
Catch ex As Exception
Exception = ex.Message
End Try
' Close your connection
If DBCon.State = ConnectionState.Open Then DBCon.Close()
End Sub
' Include query & command params
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New OleDbParameter(Name, Value)
Params.Add(NewParam)
End Sub
End Class
Without knowledge of the Access class, I have to recommend a different approach to querying the database. It is important to make sure that the database is not vulnerable to SQL injection, be it deliberate or accidental. The way to do that is to use what are known as SQL parameters: instead of putting the value in the query string, the value is supplied separately.
Private Function EmployeeSearchwithID(personalNr As String) As String
Dim mitarbeiter As String = String.Empty
Dim sql = "SELECT [Vorname], [Name] from [TA-Personal] WHERE [Personal_Nr] = ?;"
Using conn As New OleDbConnection("your connection string"),
cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "#PersonalNr",
.OleDbType = OleDbType.VarChar,
.Size = 12,
.Value = personalNr})
conn.Open()
Dim rdr = cmd.ExecuteReader()
If rdr.Read() Then
mitarbeiter = rdr.GetString(0) & " " & rdr.GetString(1)
End If
End Using
Return mitarbeiter
End Function
Private Sub tbxUserInput_KeyDown(sender As Object, e As KeyEventArgs) Handles tbxUserInput.KeyDown
If e.KeyCode = Keys.Enter Then 'employeeIDnumbersSelect()
Dim employeeName = EmployeeSearchwithID(tbxUserInput.Text.Trim())
If String.IsNullOrEmpty(employeeName) Then
MessageBox.Show("Not found.", "Problem", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
Label5.Text = employeeName
End If
End If
End Sub
The Using command makes sure that the "unmanaged resources" involved in querying a database are cleaned up afterwards, even if something goes wrong.
You will need to change the value of OleDbType.VarChar and .Size = 12 to match the type and size of that column in the database.
The name of the parameter is only for convenience with OleDb because it is ignored in the actual query, which uses "?" as a placeholder. Please see OleDbCommand.Parameters Property for full information.
If it still does not work, then please enter the ID manually in the tbxUserInput and see if you can make it work that way.
Hang on... tbxUserInput.ToString should be tbxUserInput.Text. But everything else I wrote still applies.

Database insert only works with integers, not strings

I'm attempting to insert into my database but this code only works when the variables are integers, any reason for this? Could using parameters fix this?
Public Class Floshcods
Private CardCodes As Integer
Private KeyWord As String
Private Definition As String
Public Sub New(ByVal CC As Integer)
CardCodes = CC
KeyWord = InputBox("Enter keyword")
Definition = InputBox("Enter definiton")
End Sub
Public Function GetCardCodes() As Integer
Return CardCodes
End Function
Public Function GetKeyWord() As String
Return KeyWord
End Function
Public Function GetDefinition() As String
Return Definition
End Function
End Class
================================================================
sub new()
Dim numb
Dim cn = ConnectDB()
Dim cmd As New MySqlCommand
Dim sql = "SELECT * FROM " & Tabelname & " ORDER by CardCode desc limit 1"
cmd.Connection = cn
cmd.CommandText = sql
cn.Open()
Dim result As MySqlDataReader = cmd.ExecuteReader
result.Read()
Try
numb = result.GetString(0)
Catch ex As Exception
MessageBox.Show("The selected table has no previous cards")
numb = 0
End Try
cn.Close()
Dim cardcode As Integer = numb + 1
Dim p As New Floshcods(cardcode)
Me.Controls("words" & 0).Text = p.GetKeyWord
Me.Controls("words" & 1).Text = p.GetDefinition
sql = "insert into " & Tabelname & " (CardCode,Keyword,Definition) VALUES (" & cardcode & ", " & p.GetKeyWord & ", " & p.GetDefinition & ");"
cmd.CommandText = sql
Try
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
Catch ex As Exception
MessageBox.Show("failed to add card")
End Try
end
If you need more of my code to understand, please ask.
The error I get is MySql.Data.MySqlClient.MySqlException: 'Unknown column 'test' in 'field list'.
Yes, the problem would be solved if you used SQL parameters for the values in the SQL query.
There are a few other changes that you might like to make to your code too:
It is usual to use properties rather than functions for values in a class.
Avoid Try..Catch where possible, e.g. if you can check for a value instead of having an error thrown, do so.
Some classes in .NET need to have .Dispose() called on their instances to tell it to clean up "unmanaged resources". That can be done automatically with the Using statement.
Option Strict On is useful to make sure that variable types are correct. You will also want Option Explict On. Option Infer On saves some keystrokes for when variable declarations have types obvious to the compiler.
So I suggest that you use:
Public Class Floshcods
Public Property CardCode As Integer
Public Property Keyword As String
Public Property Definition As String
Public Sub New(ByVal cardCode As Integer)
Me.CardCode = cardCode
Me.Keyword = InputBox("Enter keyword")
Me.Definition = InputBox("Enter definiton")
End Sub
End Class
and
Dim latestCardCode As Integer = 0
Dim sql = "SELECT CardCode FROM `" & Tabelname & "` ORDER BY CardCode DESC LIMIT 1;"
Using cn As New MySqlConnection("your connection string"),
cmd As New MySqlCommand(sql, cn)
cn.Open()
Dim rdr = cmd.ExecuteReader()
If rdr.HasRows Then
latestCardCode = rdr.GetInt32(0)
Else
MessageBox.Show("The selected table has no previous cards.")
End If
End Using
Dim cardcode = latestCardCode + 1
Dim p As New Floshcods(cardcode)
Me.Controls("words0").Text = p.Keyword
Me.Controls("words1").Text = p.Definition
sql = "INSERT INTO `" & Tabelname & "` (CardCode,Keyword,Definition) VALUES (#CardCode, #Keyword, #Definition);"
Using cn As New MySqlConnection("your connection string"),
cmd As New MySqlCommand(sql, cn)
cmd.Parameters.Add(New MySqlParameter With {.ParameterName = "#CardCode", .MySqlDbType = MySqlDbType.Int32, .Value = cardcode})
cmd.Parameters.Add(New MySqlParameter With {.ParameterName = "#Keyword", .MySqlDbType = MySqlDbType.VarChar, .Size = 64, .Value = p.Keyword})
cmd.Parameters.Add(New MySqlParameter With {.ParameterName = "#Definition", .MySqlDbType = MySqlDbType.VarChar, .Size = 99, .Value = p.Definition})
cn.Open()
Dim nRowsAdded As Integer = cmd.ExecuteNonQuery()
cn.Close()
If nRowsAdded = 0 Then
MessageBox.Show("Failed to add card.")
End If
End Using
You will need to change the .MySqlDbType and .Size to match how they are declared in the database.
I put backticks around the table name to escape it in case a reserved word is used or the name has spaces in it.
I changed the Functions to Properties in the Floshcods class and moved the InputBoxes to the User Interface code.
Public Class Floshcods
Public Property CardCodes As Integer
Public Property KeyWord As String
Public Property Definition As String
Public Sub New(ByVal CC As Integer)
CardCodes = CC
End Sub
End Class
I pulled out the data access code to separate methods so it will be easy to refactor to a data access layer. Also a method should be doing a single job and your Sub New was doing too much.
Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
Always use parameters to avoid Sql injection. Datatypes are guesses. Check your database for the actual types.
Sub New()
Dim TableName = "SomeTableName"
Dim numb = GetMaxCarCode(TableName)
Dim cardcode As Integer = numb + 1
Dim p As New Floshcods(cardcode)
p.KeyWord = InputBox("Enter keyword")
p.Definition = InputBox("Enter definiton")
Controls("words0").Text = p.KeyWord
Controls("words1").Text = p.Definition
InsertFloshcods(TableName, p)
End Sub
Private Function GetMaxCarCode(Tablename As String) As Integer
Dim numb As Integer
Using cn As New MySqlConnection("Your connection string."),
cmd As New MySqlCommand($"Select MAX(CardCode) From {Tablename};", cn)
cn.Open()
numb = CInt(cmd.ExecuteScalar)
End Using
Return numb
End Function
Private Sub InsertFloshcods(TableName As String, f As Floshcods)
Using cn As New MySqlConnection("your connection String"),
cmd As New MySqlCommand($"Insert Into {TableName} (CardCode, Keyword, Definition) Values (#Code, #Keyword, #Def);", cn)
With cmd.Parameters
.Add("#Code", MySqlDbType.Int32).Value = f.CardCodes
.Add("#Keyword", MySqlDbType.VarChar).Value = f.KeyWord
.Add("#Def", MySqlDbType.VarChar).Value = f.Definition
End With
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub

Issue connecting to MySQL using a Class for Connectionstring and Command?

Apologies for the poor wording in the title, I'm new to OOP VB and I have no idea how to describe the problem I'm having!
I'm attempting to create a login form that's connecting to MySQL via a class that handles the logging in.
It connects no problem but I'm having issues with creating an SQL command to pull data from the database.
Here's the SQLConnection Class
Imports MySql.Data.MySqlClient
Imports System.Threading
Public Class SQLConnection
Private serverhost As String
Private db As String
Private userid As String
Private pwd As String
Private Shared cn As New MySqlConnection
Private Shared commandstring As New MySqlCommand
Public Property Server As String
Get
Return serverhost
End Get
Set(ByVal value As String)
serverhost = value
End Set
End Property
Public Property Database As String
Get
Return db
End Get
Set(ByVal value As String)
db = value
End Set
End Property
Public Property User As String
Get
Return userid
End Get
Set(ByVal value As String)
userid = value
End Set
End Property
Public Property Password As String
Get
Return pwd
End Get
Set(ByVal value As String)
pwd = value
End Set
End Property
Public Property command As MySqlCommand
Get
Return commandstring
End Get
Set(ByVal value As MySqlCommand)
commandstring = value
End Set
End Property
Private Shared ReadOnly Property Conn As MySqlConnection
Get
Return cn
End Get
End Property
Public Shared Function TryConn(ByVal obj As SQLConnection) As Boolean
Try
Dim connectionstring As String =
"server=" & obj.Server &
";database=" & obj.Database &
";user id=" & obj.User &
";password=" & obj.Password
cn = New MySqlConnection
cn.ConnectionString = connectionstring
If cn.State = ConnectionState.Closed Then
cn.Open()
End If
Return True
cn.ConnectionString = ""
Catch ex As Exception
Return False
End Try
End Function
End Class
Here's the login form Code snippet:
Try
Dim Conn As New SQLConnection
Dim reader As MySqlDataReader
With Conn
.Server = "localhost"
.Password = ""
.User = "root"
.Database = "customers"
End With
If SQLConnection.TryConn(Conn) = True Then
Dim Query As String
Query = String.Format("SELECT * FROM users WHERE Username = '{0}' AND Password = '{1}'", Me.UsernameTextBox.Text.Trim(), Me.PasswordTextBox.Text.Trim())
sql = New MySqlCommand(Query, Conn)
reader = sql.ExecuteReader
Dim count As Integer
count = 0
While reader.Read
count = count + 1
End While
If count = 1 Then
Me.Hide()
sqlloading.Show()
ElseIf count > 1 Then
errorform.FlatAlertBox1.Text = "Username and password are duplicate"
errorform.Show()
Else
errorform.FlatAlertBox1.Text = "Wrong username or password"
errorform.Show()
End If
Me.Hide()
Else
End If
Catch
End Try
When running this I get
"Value of type 'WindowsApplication1.SQLConnection' cannot be converted to 'MySql.Data.MySqlClient.MySqlConnection'.
The problem causing the error message appears to be on this line:
sql = New MySqlCommand(Query, Conn)
Because Conn is an instance of your SQLConnection type, but has to be a MySql.Data.MySqlClient.MySqlConnection instance, that you have created as a private property of SQLConnection.
You need to make a few changes:
Make Conn and TryConn methods normal, non shared methods
Make the cn field non shared.
Have the SQLConnection class implement IDisposable, making sure to dispose cn when it is disposed.
Change the login form code block to the below:
Try
Using Conn As New SQLConnection
With Conn
.Server = "localhost"
.Password = ""
.User = "root"
.Database = "customers"
End With
If SQLConnection.TryConn(Conn) = True Then
Const Query As String = "SELECT * FROM users WHERE Username = #username AND Password = #password"
' The line below fixes the error.
Using sql As MySqlCommand = New MySqlCommand(Query, Conn.Conn)
sql.Parameters.AddWithValue("#username", Me.UsernameTextBox.Text.Trim())
sql.Parameters.AddWithValue("#password", Me.PasswordTextBox.Text.Trim())
Using reader As MySqlDataReader = sql.ExecuteReader
Dim count As Integer
count = 0
While reader.Read
count = count + 1
End While
If count = 1 Then
Me.Hide()
sqlloading.Show()
ElseIf count > 1 Then
errorform.FlatAlertBox1.Text = "Username and password are duplicate"
errorform.Show()
Else
errorform.FlatAlertBox1.Text = "Wrong username or password"
errorform.Show()
End If
Me.Hide()
End Using
End Using
End If
End Using
Catch
' at least log the error?
End Try
This will solve you immediate problems, but there is room left for improvement. Instead of formatting your SQL yourself like this:
Query = String.Format(
"SELECT * FROM users WHERE Username = '{0}' AND Password = '{1}'",
Me.UsernameTextBox.Text.Trim(), Me.PasswordTextBox.Text.Trim())
You should really use SQL parameters to prevent SQL injection attacks, refer to the Little Bobby Tables story for reasons why. I have updated the code snippet above to improve this.
A final remark: you are now storing passwords as unencrypted plain text in your database. That is considered to be not secure. Passwords should always be stored and transmitted across the wire in an encrypted format.
Your Dim Conn As New SQLConnection is using the SQLConnection class.
If you're using MySQL, try have a look here.
I added the whole function from the login form to the SQLConnection class
Then Called it using:
Try
Dim Conn As New sqltryclass
With Conn
.Server = "localhost"
.Password = ""
.User = "root"
.Database = "adminapp"
End With
If sqltryclass.TryLogin(Conn) = True Then
Me.Hide()
sqlloading.Show()
Else
End If
Catch
End Try

Close connection after calling ExcuteScalar

i have the following function, the problem is since im using ExecuteScalar, the connection never closes when using any other function again...
Public Function Valor(tabla As String, campos As String, condicion As String)
cn.Open()
Dim sql As String = "SELECT " & campos & " FROM " & tabla & " WHERE " & condicion
comando = New SqlCommand(sql, cn)
Return comando.ExecuteScalar
If cn.State = ConnectionState.Open Then
cn.Close()
End If
End Function
This Function returns me a Time value from SQL time(7) to TIMESPAN on the app, i am able to get the value but Since Return skips anything after it, connection is not closed.
ANy idea how to close the connection this?
or there is another method on how can i get the value of my query.
Thanks in advance
First of all, connections in .Net work best when you create an entirely new object for each query. Don't try to re-use the same connection all the time.
Second, that code could still leak connections even if you had closed the connection before returning, because it would never reach .Close() function call if an exception is thrown.
Finally, that code is horribly vulnerable to sql injection. It's practically begging to get hacked.
Here is code that solves all three problems:
Public Function Valor(ByVal sql As String, ByVal ParamArray condicion() As SqlParameter)
'cnString is a made-up string variable for the connection string that you will create in the same place (and instead of) that you currently have cn
Using cn As New SqlConnection(cnString), _
cmd As New SqlCommand(sql, cn)
If condicion IsNot Nothing Then cmd.Parameters.AddRange(condicion)
cn.Open()
Return cmd.ExecuteScalar()
End Using
End Function
Instead of returning immediately, store the result in a variable, clean up everything, then return the cached variable:
Public Function Valor(tabla As String, campos As String, condicion As String)
cn.Open()
Dim sql As String = "SELECT " & campos & " FROM " & tabla & " WHERE " & condicion
comando = New SqlCommand(sql, cn)
Dim retorno As Object = comando.ExecuteScalar()
If cn.State = ConnectionState.Open Then
cn.Close()
End If
Return retorno
End Function