that's my first time here, I'm going mad because of this problem I have:
I'm developing a windows form application with VB.NET using multiple types of connections(mysql,odbc and SQL server) everything works fine until I get into MySQL..
MySQL server is a physical windows 7 pc, I connect to it through IPSEC VPN TUNNEL.
I need to perform 2 MySQL connections every x seconds, if I get some type of result after the first connection then I'll open the second one, and so on every x seconds(that's all wrote in my timer.tick event handler).
The problem is that quite often some connections on MySQL server keep staying alive(ESTABLISHED) on MySQL server and I can't find out why... code looks fine, there are both open and close methods declared at the right time, I've also tried Dispose,ClearPool and ClearAllPools methods but I keep having those connections up until I close my program or it reaches connection limit.
Here's the code:
Class connection:
Public Sub connMySQL()
Dim connstring As String
Try
If stabilimento = "1PR" Then
If cesoia = "" Then
connstring = "server=192.168.123.18;userid=xx;password=xx;database=xx;Connect Timeout=30"
Else
connstring = "server=192.168.123.253;userid=xx;password=xx;database=xx;Connect Timeout=30"
End If
End If
If stabilimento = "2PR" Then
If cesoia = "" Then
connstring = "server=192.168.1.18;userid=xx;password=xx;database=xx;Connect Timeout=30"
Else
connstring = "server=192.168.123.253;userid=root;password=xx;database=xx;Connect Timeout=30"
End If
End If
conMySql = New MySqlConnection(connstring)
If conMySql.State = ConnectionState.Closed Then
conMySql.Open()
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Class where the iteration is performed:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
connMySQL()
comm = New MySqlCommand("SELECT count_1,count_2,start_stop,data_ora,id FROM plc_contatori where plc_nome='" + plc_nome + "' and data_ora > '" + data_ieri.ToString("yyyy/MM/dd") + "' order by data_ora desc limit 1", conMySql)
dr = comm.ExecuteReader()
While (dr.Read())
count_1(0) = dr.GetValue(0)
start_stop(0) = dr.GetValue(2)
data_ora(0) = dr.GetValue(3)
If id <> dr.GetValue(4) And count_2(0) <> dr.GetValue(1) Then
id = dr.GetValue(4)
count_2(0) = dr.GetValue(1)
Else
Exit Sub
End If
End While
dr.Close()
dr.Dispose()
conMySql.Close()
conMySql.Dispose()
conMySql.ClearPool(conMySql)
conMySql.ClearAllPools()
If Not conMySql Is Nothing Then conMySql = Nothing
comm.Dispose()
If start_stop(0) = 1 Then
Exit Sub
End If
Dim dum_count_2 As Integer = count_2(0) - 1
connMySQL()
comm = New MySqlCommand("select count_1,count_2,start_stop,data_ora from plc_contatori where plc_nome='" + plc_nome + "' and data_ora > '" + data_ieri.ToString("yyyy/MM/dd") + "' AND count_2=" + dum_count_2.ToString + " ORDER BY data_ora desc limit 1", conMySql)
dr = comm.ExecuteReader()
While (dr.Read())
count_1(1) = dr.GetValue(0)
count_2(1) = dr.GetValue(1)
start_stop(1) = dr.GetValue(2)
data_ora(1) = dr.GetValue(3)
End While
dr.Close()
dr.Dispose()
conMySql.Close()
conMySql.Dispose()
conMySql.ClearPool(conMySql)
conMySql.ClearAllPools()
If Not conMySql Is Nothing Then conMySql = Nothing
comm.Dispose()
If count_1(0) = count_1(1) And start_stop(1) <> 1 And count_2(0) <> count_2(1) Then
'sub that reads some values from an odbc connection
CheckFermo()
End If
End Sub
NOTE that variables that I have not declared in this portion of code are declared in the public class of the form.
I'm wondering what could be wrong... maybe the 2nd connection is being established before the 1st one gets closed by the server?
I changed the connMySQL method to a function that returns the connection string. I have declared several variables so the code makes sense. I made several assumptions about datatypes. You may have to change this back to String and VarChar if these values are actually stored as strings. (I hope they are not)
You could use a single connection but all the assignments and comparisons would occur with an open connection.
Private stabilimento As String
Private cesoia As String
Public Function connMySQL() As String
Dim connstring As String
Select Case True
Case stabilimento = "1PR" And cesoia = ""
connstring = "server=192.168.123.18;userid=xx;password=xx;database=xx;Connect Timeout=30"
Case stabilimento = "2PR" And cesoia = ""
connstring = "server=192.168.1.18;userid=xx;password=xx;database=xx;Connect Timeout=30"
Case Else
connstring = "server=192.168.123.253;userid=root;password=xx;database=xx;Connect Timeout=30"
End Select
Return connstring
End Function
Private count_1(10) As Integer
Private count_2(10) As Integer
Private start_stop(10) As Integer
Private data_ora(10) As Date
Private id As Integer
Private plc_nome As String
Private data_ieri As Date
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Using dt As New DataTable
Using cn As New MySqlConnection(connMySQL),
comm = New MySqlCommand("SELECT count_1,count_2,start_stop,data_ora,id
FROM plc_contatori
where plc_nome= #plcNome and data_ora > #dataOra
order by data_ora desc
limit 1", cn)
comm.Parameters.Add("plcNome", MySqlDbType.VarChar).Value = plc_nome
comm.Parameters.Add("dataOra", MySqlDbType.Date).Value = data_ieri '.ToString("yyyy/MM/dd")
cn.Open()
Using dr = comm.ExecuteReader
dt.Load(dr)
End Using 'closes and disposes reader
End Using 'closes and dispose connection and command
count_1(0) = CInt(dt(0)(0))
start_stop(0) = CInt(dt(0)(2))
data_ora(0) = CDate(dt(0)(3))
If id <> CInt(dt(0)(4)) AndAlso count_2(0) <> CInt(dt(0)(1)) Then
id = CInt(dt(0)(4))
count_2(0) = CInt(dt(0)(1))
Else
Exit Sub
End If
End Using 'disposes DataTable
If start_stop(0) = 1 Then
Exit Sub
End If
Dim dum_count_2 As Integer = count_2(0) - 1
Using dt As New DataTable
Using cn As New MySqlConnection(connMySQL),
comm As New MySqlCommand("select count_1,count_2,start_stop,data_ora
from plc_contatori
where plc_nome= #plcNome
and data_ora > #dataOra
AND count_2= #count2
ORDER BY data_ora desc
limit 1", cn)
comm.Parameters.Add("#plcNome", MySqlDbType.VarChar).Value = plc_nome
comm.Parameters.Add("#dataOra", MySqlDbType.Date).Value = data_ieri '.ToString("yyyy/MM/dd")
comm.Parameters.Add("#count2", MySqlDbType.Int32).Value = dum_count_2 '.ToString
cn.Open()
Using dr = comm.ExecuteReader()
dt.Load(dr)
End Using
End Using
count_1(1) = CInt(dt(0)(0))
count_2(1) = CInt(dt(0)(1))
start_stop(1) = CInt(dt(0)(2))
data_ora(1) = CDate(dt(0)(3))
End Using
If count_1(0) = count_1(1) AndAlso start_stop(1) <> 1 AndAlso count_2(0) <> count_2(1) Then
'sub that reads some values from an odbc connection
CheckFermo()
End If
End Sub
Related
Unfortunately, I can't get any further. Working with vs2019 and vb. Created a cascading DropDownList (country, state, region). It works perfectly for country where I don't have to use AddWithValue (where). With state where I have to use AddWithValue (where), I don't get it baked. All IDs are defined as integers. The relevant code:
Protected Sub idLand_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
DropDownBundesland.Items.Clear()
DropDownBundesland.Items.Add(New ListItem("--Select Country--", ""))
DropDownRegion.Items.Clear()
DropDownRegion.Items.Add(New ListItem("--Select City--", ""))
DropDownBundesland.AppendDataBoundItems = True
Dim strConnString As [String] = ConfigurationManager _
.ConnectionStrings("conString").ConnectionString
Dim strQuery As [String] = "Select Bundesland, idBundesland, idLand from Campingplatz ORDER BY Bundesland ASC where idLand = #LandID Group BY Bundesland"
Dim con As New MySqlConnection(strConnString)
Dim cmd As New MySqlCommand()
cmd.Parameters.AddWithValue("#LandID", MySqlDbType.Decimal).Value = DropDownLand.SelectedItem.Value
cmd.CommandType = CommandType.Text
cmd.CommandText = strQuery
cmd.Connection = con
Try
con.Open()
DropDownBundesland.DataSource = cmd.ExecuteReader()
DropDownBundesland.DataTextField = "Bundesland"
DropDownBundesland.DataValueField = "idBundesland"
DropDownBundesland.DataBind()
If DropDownBundesland.Items.Count > 1 Then
DropDownBundesland.Enabled = True
Else
DropDownBundesland.Enabled = False
DropDownRegion.Enabled = False
End If
Catch ex As Exception
'Throw ex
Finally
con.Close()
con.Dispose()
End Try
End Sub
Please help!
this query is wrong:
Dim strQuery As [String] = "Select Bundesland, idBundesland, idLand from Campingplatz ORDER BY Bundesland ASC where idLand = #LandID Group BY Bundesland"
you must change the order of WHERE, ORDER BY and GROUP BY like:
Dim strQuery As [String] = "Select Bundesland, idBundesland, idLand from Campingplatz WHERE idLand = #LandID Group BY Bundesland ORDER BY Bundesland ASC"
Here you can see the Ssyntax: https://mariadb.com/kb/en/select/
I don't like to mix user interface code with database code. The database code should be independent of the kind of application where it is used.
Connections, Commands and DataReaders need to have their Dispose methods called so they can release unmanaged resources. You are provided with Using...End Using blocks to accomplish this and also close the connection.
You are mixing apples and oranges building the parameters collection. I showed both Add and AddWithValue in the code.
Please see my notes in the Catch block.
I would make the strConString a class level variable if the database is accessed by any other methods in the class.
Protected Sub idLand_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
DropDownBundesland.Items.Clear()
DropDownBundesland.Items.Add(New ListItem("--Select Country--", ""))
DropDownRegion.Items.Clear()
DropDownRegion.Items.Add(New ListItem("--Select City--", ""))
DropDownBundesland.AppendDataBoundItems = True
Dim dt As DataTable = Nothing
Try
dt = GetDropDownData(CDec(DropDownLand.SelectedItem.Value))
Catch ex As Exception
'Where would you be throwing it to? This is an event procedure so is not "called"
'Alert the user, maybe log the error
Exit Sub
End Try
DropDownBundesland.DataSource = dt
DropDownBundesland.DataTextField = "Bundesland"
DropDownBundesland.DataValueField = "idBundesland"
DropDownBundesland.DataBind()
If DropDownBundesland.Items.Count > 1 Then
DropDownBundesland.Enabled = True
Else
DropDownBundesland.Enabled = False
DropDownRegion.Enabled = False
End If
End Sub
Private strConnString As [String] = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Private Function GetDropDownData(LandID As Decimal) As DataTable
Dim dt As New DataTable
Dim strQuery As [String] = "Select Bundesland, idBundesland, idLand
From Campingplatz
Where idLand = #LandID
Group BY Bundesland
ORDER BY Bundesland ASC "
Using con As New MySqlConnection(strConnString),
cmd As New MySqlCommand(strQuery, con)
cmd.Parameters.Add("#LandID", MySqlDbType.Decimal).Value = LandID
'or cmd.Parameters.AddWithValue("#LandID", LandID)
con.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
I'm making a tool to help a company with there staff holiday (staff holiday calculator)
I connected myself by vb and its connection to the database but I can't get any result
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim conn As New api()
Dim adapter As New MySqlDataAdapter()
Dim table As New DataTable()
Dim command As New MySqlCommand("SELECT `Full_Name`, `Job`, `Free_Days` FROM `Holiday` WHERE `Username`= '#name'", conn.getConnection())
command.Parameters.Add("#name", MySqlDbType.VarChar).Value = api.id
Try
conn.getConnection.Open()
adapter.SelectCommand = command
adapter.Fill(table)
Dim sqlReader As MySqlDataReader = command.ExecuteReader()
While sqlReader.Read()
namee = sqlReader("Full_Name").ToString()
job = sqlReader("Job").ToString()
days = sqlReader("Free_Days").ToString()
MsgBox(sqlReader("Full_Name").ToString())
End While
Label2.Text = "Name : " + namee
Label3.Text = "Job : " + job
Label8.Text = "Holiday Free Days : " & days
Catch ex As MySql.Data.MySqlClient.MySqlException
MsgBox(ex.Message)
End Try
End Sub
I didn't get any MsgBox and there is no error and the label text didn't change
I don't have MySQL, but based on MSSQL try something like this:
Dim namee, job, days As String
Dim commandText As String = "SELECT `Full_Name`, `Job`, `Free_Days` FROM `Holiday` WHERE `Username`= '#name'"
Dim conn As New api()
Using adapter As New MySqlDataAdapter(commandText, conn.getConnection())
adapter.SelectCommand.Parameters.Add("#name", MySqlDbType.VarChar).Value = api.id
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count = 0 Then
MessageBox.Show("No rows found", "ERROR")
Else
With table(0)
namee = .Item("Full_Name")
job = .Item("Job")
days = .Item("Free_Days")
End With
End If
End Using
please, can anybody explain why this code is not working?
Connection to mysql is made via mysql odbc driver (latest).
Parameter in Select command is not recognized.
I also tried to replace #param1 in Select command:
Select product_id from product where model = ?
code still not working.
Sub Main()
Dim DBCONT As New Odbc.OdbcConnection
Dim strConn As String = "DSN=MyDSN"
DBCONT.ConnectionString = strConn
DBCONT.Open()
Dim cmd As New Odbc.OdbcCommand
With cmd
.CommandText = "SELECT product_id FROM products WHERE model = #param"
.Connection = DBCONT
End With
Dim param1 As Odbc.OdbcParameter
param1 = cmd.CreateParameter()
With param1
.ParameterName = "#param"
.OdbcType = Odbc.OdbcType.VarChar
.Size = 30
.Value = "TESTVALUE"
End With
Dim reader As Odbc.OdbcDataReader
reader = cmd.ExecuteReader
Console.WriteLine(cmd.CommandText.ToString)
'this line displays "Select product_id from products where model = #param"
'instead of "Select product_id from products where model = "TESTVALUE"..
'WHY??
While reader.Read
Console.WriteLine(reader(0))
Console.WriteLine()
End While
Console.ReadLine()
DBCONT.Close()
reader = Nothing
cmd = Nothing
End Sub
Where it says:
".CommandText = "SELECT product_id FROM products WHERE model = #param"
Change it to:
".CommandText = "SELECT product_id FROM products WHERE model = '#param'"
(I've put ' ' around the #param, keep in mind this is different to the " " that is surrounding this)
I'm not 100% sure but I'll post this as an answer anyway because I think it's correct:
Dim cmd As New Odbc.OdbcCommand
With cmd
.CommandText = "SELECT product_id FROM products WHERE model = :param"
.Connection = DBCONT
End With
Dim param1 As Odbc.OdbcParameter
param1 = cmd.CreateParameter()
With param1
.ParameterName = "param"
.OdbcType = Odbc.OdbcType.VarChar
.Size = 30
.Value = "TESTVALUE"
End With
Thanks for your help. This code is already working:
Sub Main()
Dim DBCONT As New Odbc.OdbcConnection
Dim strConn As String = "DSN=MyDSN"
DBCONT.ConnectionString = strConn
DBCONT.Open()
Dim cmd As New Odbc.OdbcCommand
With cmd
.CommandText = "SELECT product_id FROM products WHERE model LIKE ?"
//it seems it is important to add paramater right after commandtext
.Parameters.Add("#param", OdbcType.VarChar).Value = "%" + "TESTVALUE" + "%"
.Connection = DBCONT
End With
Dim reader As Odbc.OdbcDataReader
reader = cmd.ExecuteReader
Console.WriteLine(cmd.CommandText.ToString)
//it should display SELECT product_id FROM products WHERE model LIKE ?
While reader.Read
Console.WriteLine(reader(0))
Console.WriteLine()
End While
Console.ReadLine()
DBCONT.Close()
reader = Nothing
cmd = Nothing
End Sub
I'm working on my project which displays a list of employee. here, the information and picture of the employee will be shown. my project can now show the list of employees in the listbox and when I double click on an employee, his/her profile will be shown on a textbox. my problem is that i can't make their pictures to show in the picturebox. I already stored their picture on a table in my database along with their id, name, and profile. It only shows the picture of the first employee on the table. can anybody help me?
here's what I already done:
I populated the listbox:
Call Connect()
With Me
STRSQL = "Select employee_name from Employees"
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
reader = myCmd.ExecuteReader
If (reader.Read()) Then
reader.Close()
adptr.SelectCommand = myCmd
adptr.Fill(dt)
lstEmployee.DisplayMember = "employee_name"
lstEmployee.ValueMember = "employee_id"
If dt.Rows.Count > 0 Then
For i As Integer = 0 To dt.Rows.Count - 1
lstEmployee.Items.Add(dt.Rows(i)("employee_name"))
Next
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End With
here's how I show the info on textbox
Dim FileSize As UInt32
Dim mStream As New System.IO.MemoryStream()
Dim arrImage() As Byte = mStream.GetBuffer()
FileSize = mStream.Length
Dim cmd As New MySqlCommandBuilder
Call Connect()
With Me
STRSQL = "select employee_name, profile from Employees where employee_id = " & lstEmployee.SelectedIndex
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
reader = myCmd.ExecuteReader
If (reader.Read()) Then
txtName.Text = reader("employee_name")
txtProfile.Text = reader("profile")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
myConn.Close()
End Try
adptr.SelectCommand = myCmd
dt = New DataTable
adptr = New MySqlDataAdapter("select picture from Employees", myConn)
cmd = New MySqlCommandBuilder
adptr.Fill(dt)
Dim lb() As Byte = dt.Rows(0).Item("picture")
Dim lstr As New System.IO.MemoryStream(lb)
pix.Image = Image.FromStream(lstr)
pix.SizeMode = PictureBoxSizeMode.StretchImage
lstr.Close()
You miss the where clause is must be like to search a one employee to view there image.
adptr = _
New MySqlDataAdapter("select picture from Employees " + _
"where employee_id = " & lstEmployee.SelectedIndex, myConn)
cmd = New MySqlCommandBuilder
adptr.Fill(dt)
Dim lb() As Byte = dt.Rows(0).Item("picture")
Dim lstr As New System.IO.MemoryStream(lb)
pix.Image = Image.FromStream(lstr)
pix.SizeMode = PictureBoxSizeMode.StretchImage
lstr.Close()
P.S.: You must study the LINQ (Language-Integrated Query) for better approach.
Good day everyone. I am trying to create a program that will transfer all of the contents of a text file into a database. So far, my code works, but my code only inserts the first line of the text file into the database. What should I add to solve the problem? I am noob at programming sorry.
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim filename As String = "C:\Users\user\desktop\swipe.txt"
Dim Query As String
Dim data As String = System.IO.File.ReadAllText(filename)
Dim Loc, _date, time, temp, id As String
Loc = data.Substring(0, 3)
_date = data.Substring(3, 8)
time = data.Substring(11, 4)
temp = data.Substring(15, 3)
id = data.Substring(18, 3)
Query = "INSERT INTO tbl_entrance_swipe VALUES ('" + Loc + "','" + _date + "','" + time + "','" + temp + "','" + id + "')"
Dim con As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=cph;User ID=root;Password=;")
Try
con.Open()
Dim sql As MySqlCommand = New MySqlCommand(Query, con)
sql.ExecuteNonQuery()
MsgBox("Record is Successfully Inserted")
con.Close()
Catch ex As Exception
con.Close()
MsgBox("Record is not Inserted" + ex.Message)
End Try
End Sub
End Class
You are using File.ReadAllText which reads the complete text of the file. You want to read line by line, therefore you can use File.ReadLines(deferred executed) or File.ReadAllLines(reads all into a String()).
You should also use sql-parameters to prevent sql-injection and incorrect implicit type conversions or localization issues. Finally, use the Using statement to ensure that all unmanaged resources are disposed (f.e. the connection gets closed even on error):
Dim filename As String = "C:\Users\user\desktop\swipe.txt"
Dim allLines As String() = File.ReadAllLines(filename)
Dim query As String = "INSERT INTO tbl_entrance_swipe VALUES (#Loc, #Date, #Time, #Temp, #Id)"
Using con As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=cph;User ID=root;Password=;")
con.Open()
Using cmd As New MySql.Data.MySqlClient.MySqlCommand(query, con)
For Each line In allLines
Dim loc, dt, time, temp, id As String
loc = line.Substring(0, 3)
dt = line.Substring(3, 8)
time = line.Substring(11, 4)
temp = line.Substring(15, 3)
id = line.Substring(18, 3)
cmd.Parameters.Clear()
Dim pLoc As New MySql.Data.MySqlClient.MySqlParameter("#Loc", MySqlDbType.VarChar)
pLoc.Value = loc
cmd.Parameters.Add(pLoc)
Dim pDate As New MySql.Data.MySqlClient.MySqlParameter("#Date", MySqlDbType.VarChar)
pDate.Value = dt
cmd.Parameters.Add(pDate)
Dim pTime As New MySql.Data.MySqlClient.MySqlParameter("#Time", MySqlDbType.VarChar)
pTime.Value = time
cmd.Parameters.Add(pTime)
Dim pTemp As New MySql.Data.MySqlClient.MySqlParameter("#Temp", MySqlDbType.VarChar)
pTemp.Value = temp
cmd.Parameters.Add(pTemp)
Dim pId As New MySql.Data.MySqlClient.MySqlParameter("#Id", MySqlDbType.VarChar)
pId.Value = id
cmd.Parameters.Add(pId)
cmd.ExecuteNonQuery()
Next
MsgBox("All records were inserted successfully")
con.Close()
End Using
End Using