vb net max_user_connections to mysql - mysql

I have a pc program used by dozens of people, and with the increase in people connecting to a database, the program began to throw the error with a large number of database connections. I checked the database after each query creates a process that is in the database as "sleep" if you exceeded the number 50 is the above error crashes. How can I remedy this if the problem lies with the program or hosting?
Database screen ;
http://obrazki.elektroda.pl/5375287900_1423553806.png
Code:
Public Sub loginUser(ByVal sql As String)
Try
Dim maxrow As Integer
con.Open()
dt = New DataTable
With cmd
.Connection = con
.CommandText = sql
End With
da.SelectCommand = cmd
da.Fill(dt)
maxrow = dt.Rows.Count
If maxrow > 0 Then
Form1.Show()
Else
Label3.Text = ("Invalid Username or Password!")
Label3.Visible = True
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
da.Dispose()
End Sub
Private Sub InsertData()
sql = "SELECT * from users WHERE login = '" & (username.Text) & "' and pass = '" & StringtoMD5(password.Text) & "'and banned = '" & 0 & "'"
loginUser(sql)
End Sub

When using database connections a special care should be used to correctly close and dispose these connections. If you don't do that correctly you end up with stale connections kept by your program and never reused by the pooling infrastructure of ADO.NET (See ADO.NET Connection Pooling)
The code in your example above has all the checks in place and should not be the cause of your problems but, are you sure that every where in your program you follow the same pattern without forgetting to dispose the involved objects?
The using statement is a life saver here because, EVEN in case of exceptions, you could be sure that the objects enclosed by the using statement are closed and disposed returning any unmanaged resources back to the system.
Another problem is your way to build SQL Commands concatenating strings. This leads directly to SQL Injection attacks and a very poor security standard for your application.
Said that, I think you should change your loginUser method to something like this
Public Sub loginUser(ByVal sql As String, ByVal parameterList as List(Of MySqlParameter))
Try
Dim maxrow As Integer
' local variables for connection, command and adapter... '
Using con = new MySqlConnection( ..connstring here.. )
Using cmd = con.CreateCommand()
con.Open()
With cmd
.Connection = con
.CommandText = sql
.Parameters.AddRange(parameterList.ToArray())
End With
Using da = new MySqlDataAdapter(cmd)
Dim dt = New DataTable
da.Fill(dt)
maxrow = dt.Rows.Count
If maxrow > 0 Then
Form1.Show()
Else
Label3.Text = ("Invalid Username or Password!")
Label3.Visible = True
End If
End Using
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
And call it with
Private Sub InsertData()
sql = "SELECT * from users " & _
"WHERE login = #uname " & _
"AND pass = #pwd " & _
"AND banned = '0'"
Dim parameterList = new List(Of MySqlParameter)()
parameterList.Add(new MySqlParameter("#uname", MySqlDbType.VarChar))
parameterList.Add(new MySqlParameter("#pwd", MySqlDbType.VarChar))
parameterList(0).Value = username.Text
parameterList(1).Value = StringtoMD5(password.Text)
loginUser(sql, parameterList)
End Sub
As I have said, just this change alone probably don't fix your problem. You should try to find in your program where you have a situation in which the connection is not properly closed and disposed. (and, at least, replace that code with the using statement)

Related

HOW TO USE UPDATE IN SQL WITH VB

Can you please help me, what the problem of my code:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
'UPDATE Data
openCon()
Try
cmd.Connection = con
cmd.CommandText = "UPDATE emp_table SET FNAME = '" & TextBox1.Text & "', LNAME= '" & TextBox2.Text & "', AGE = '" & TextBox3.Text & "', GENDER ='" & Gender & "', OFFICE STAFF= '" & ComboBox1.Text & "' Where ID ='" & TxtID.Text & "' "
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Suceessfully Updated Record")
TxtID.Clear()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
RBMale.Checked = False
RBFemale.Checked = False
ComboBox1.Text = ""
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
There are many problems in your code and if you look around this site I think you will find many partial answers that step by step will help you solve your problems. So I try to give you an answer where all the problems are examined, discussed and solved.
First problem: How do you handle the connection.
It seems that you have a global connection instance called con that you open with openCon. This is not a good approach and always a source of problems. You always need to check if the connection is closed properly or not. For example, in the code above you have forgot to close the connection in case of exception and this will lead to other exceptions in some code not related to this one. You keep resources on the server locked to you and this will decrease the performance of every one connection to that server.
I would change your openCon to this
Public Function openCon() as MySqlConnection
Dim con as MySqlConnection = new MySqlConnection(....here connection string ...)
con.Open()
return con
End Function
This will create a new instance of the MySqlConnection every time you call this method Now you can remove the global connection instance and use the one returned by openCon in this way
Using con As MySqlConnection = openCon()
.... code that use the local con object
End Using
This will close and destroy the connection even if an exception occurs inside the Using block and the ADO.NET libraries are smart enough to use a thing called Connection Pooling to reduce the time required to build and open a connection with the same connection string.
Second problem: The syntax error.
Looking at the point of the error suggested by the message I can see a field name composed by two words separated by a space. This is fine, but then you should remember that the sql parser cannot understand this and you need to help it enclosing the two words in a backtick character (ALT+096) so the parser understand that this is a single field name. Given the fact column names are an internal information of no concern for your end user then why use spaces in column names? If possible remove the space in column names.
Third problem: Sql Injection and other syntax errors
You are concatenating strings to build an sql command. But this is an easy target for wannabe hackers. Suppose that I write in your textBox1 this string instead of a First Name: Mario'; --
Then your command becomes
UPDATE emp_table SET FNAME = 'Mario'; -- xxxxxxxxxxxx
everything after -- is considered a comment and the query is still executable, but it changes every record in emp_table to have a first name equal to Mario.
But the query could fail as well if someone writes a Last Name that contains an apostrophe like O'Leary just now the query is no more syntactically valid.
The solution to this is always one. Use Parameters.
Recap of changes to your code.
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim cmdText as String = "UPDATE emp_table SET FNAME = #fname,
LNAME= #lname, AGE = #age, GENDER =#gender,
`OFFICE STAFF` = #staff
Where ID =#id"
Using con as MySqlConnection = openCon()
Using cmd as MySqlCommand = new MySqlCommand(cmdText, con)
Try
cmd.Parameters.Add("#fname", MySqlDbType.VarChar).Value = textBox1.Text
cmd.Parameters.Add("#lname", MySqlDbType.VarChar).Value = textBox2.Text
cmd.Parameters.Add("#age", MySqlDbType.VarChar).Value = textBox3.Text
cmd.Parameters.Add("#gender", MySqlDbType.VarChar).Value = gender
cmd.Parameters.Add("#staff", MySqlDbType.VarChar).Value = combobox1.Text
cmd.Parameters.Add("#id", MySqlDbType.VarChar).Value = txtID.Text
cmd.ExecuteNonQuery()
MsgBox("Suceessfully Updated Record")
TxtID.Clear()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
RBMale.Checked = False
RBFemale.Checked = False
ComboBox1.Text = ""
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Using
End Using
End Sub
In the recap I have added parameters for every single field that you want to update. But remember. Parameters should have a Type (The MySqlDbType here) that should match the type of the field and the value should be of the same type. For example it seems improbable that Age is a varchar field. So you should convert TextBox3.Text to an integer if the field is an integer.

VB.Net with Mysql A connection attempt failed..." error arise when trying to read data from Mysql table. Insert into statement is working

I'm new to Mysql databases. I created and connected successfully a database for the local server. But "A connection attempt failed..." error arise when trying to read data from a table. "Insert into ..." statement is working. I searched for whole web for the reason. Not success. Anyone can help, please. Thank in advance...
Complete error description:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Relevant Code as follows:
following function Working and Connected successfully
Public Function Connect() As Boolean
Dim Status As Boolean
Try
conn.ConnectionString = "Server=" & Server & ";Port=3306;Database=" & DBName & ";User ID=" & UID & ";Password=" & Pwd & ";CharSet=utf8;"
conn.Open()
cmd.Connection = conn
If conn.State = ConnectionState.Open Then
Status = True
End If
Catch ex As Exception
ErrorMsg = ex.Message
Status = False
End Try
Return Status
End Function
Following Function returns the error...
Public Function getData(ByVal SQLStr As String) As MySql.Data.MySqlClient.MySqlDataReader
Dim tmpDR As MySql.Data.MySqlClient.MySqlDataReader
If conn.State = ConnectionState.Open Then
cmd.CommandText = SQLStr
tmpDR = cmd.ExecuteReader()
Else
MsgBox("Database not connected...", MsgBoxStyle.Exclamation, "Connection Error")
tmpDR = Nothing
End If
getData = tmpDR
End Function
Get rid of any class level database objects. Get rid of the Function Connect altogether. If you ever start to write
If conn.State = ConnectionState.Open Then
you should know you are doing it wrong.
Don't pass DataReader's around. The connection must remain open for them to function. Load a DataTable and pass that after the connection and command are disposed by the Using block.
If you intend to show a message box to the user, let exceptions bubble up to the user interface code.
Private ConStr As String = "Server=" & Server & ";Port=3306;Database=" & DBName & ";User ID=" & UID & ";Password=" & Pwd & ";CharSet=utf8;"
Public Function getData(ByVal SQLStr As String) As DataTable
Dim dt As New DataTable
Using conn As New MySqlConnection(ConStr),
cmd As New MySqlCommand(SQLStr)
conn.Open
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
As you can see, it only takes one simple line to create a connection. Connections are precious resources and should only be opened directly before the .Execute... and closed as soon as possible.

How do I write to a Mysql database in VB.net with a query

I am trying to make a little program that writes and reads from a Mysql database. The reading part is going well, but I am a bit stuck in the write part.
This is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Absenden.Click
Dim conn As New MySqlConnection
Dim command As MySqlCommand
Dim myConnectionString As String
myConnectionString = "server=Nothing;uid=to;pwd=see;database=here;"
conn.ConnectionString = myConnectionString
Try
conn.Open()
Dim Querywrite As String
Querywrite = "select * FROM here.message INSERT INTO message admin='" & TB_Name.Text & "' and message='" & TB_Nachricht.Text & "' and Server='" & TB_Server.Text & "' and status='" & TB_Status.Text & "' "
command = New MySqlCommand(Querywrite, connection)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
conn.Close()
End Sub
The Querywrite part is the problem I think. The input comes from Textboxes in a Windows Form.
Thanks for your help!
Perhaps, if someone shows you once then you will get the idea. The main thing is to always use parameters; not only will you avoid minor sytax and type errors but you will avoid major disasters of malicious input. I guessed at the datatypes of your fields. Please check your database for the types and adjust your code accordingly.
Private Sub InsertData()
Dim strQuery As String = "Insert Into message (admin, message, Server, status) Values (#admin, #message, #Server, #status);"
Using cn As New MySqlConnection("your connection string")
Using cmd As New MySqlCommand With {
.Connection = cn,
.CommandType = CommandType.Text,
.CommandText = strQuery}
cmd.Parameters.Add("#admin", MySqlDbType.VarString).Value = TB_Name.Text
cmd.Parameters.Add("#message", MySqlDbType.VarString).Value = TB_Nachricht.Text
cmd.Parameters.Add("#Server", MySqlDbType.VarString).Value = TB_Server.Text
cmd.Parameters.Add("#status", MySqlDbType.VarString).Value = TB_Status.Text
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
End Using
End Using
End Sub

SQL Queries and Threading

I have to execute several SQL queries and I want to use Threads for this, because this queries have to be executed every 1 second to update or get some different values of the database.
When I try to execute my code, I get the following Error:
WindowsApplication1.vshost.exe Error: 0 : There is already an open
DataReader associated with this Connection which must be closed first.
I have read on stackoverflow, that the Connection should ALWAYS be opened as late as possible and be closed as fast as possible.
Is there any solution for this Problem?
Here is my code:
Imports MySql.Data.MySqlClient
Imports System.Threading
Public Class Form1
Private server As String = Nothing
Private pass As String = Nothing
Private user As String = Nothing
Private port As String = Nothing
Private db As String = Nothing
Dim Thread1 As Thread
Dim Thread2 As Thread
Dim con As New MySqlConnection
Dim cmd As New MySqlCommand
Dim reader As MySqlDataReader
Public Sub New()
Me.server = "localhost"
Me.user = "root"
Me.pass = ""
Me.port = "3306"
Me.db = "diagnosedb"
cmd.Connection = con
con.ConnectionString = "Server = " & Me.server & ";
Port = " & Me.port & ";
Database = " & Me.db & ";
Uid = " & Me.user & ";
Pwd = " & Me.pass & ";"
Thread1 = New Thread(AddressOf Querie1)
Thread2 = New Thread(AddressOf Querie2)
Thread1.Start()
Thread2.Start()
End Sub
Private Sub Querie1()
cmd.CommandText = "UPDATE teileliste
SET verschleis = 500
WHERE ID = 1;"
Try
con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub Querie2()
cmd.CommandText = "UPDATE teileliste
SET verschleis = 0
WHERE ID = 20;"
Try
con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
End Class
Create and close a new connection within the Querie1 and Querie2 methods. You can't have multiple concurrent operations going on with one connection. (Even if you could, you're closing the connection in both methods. One method might try to close it while the other is using it.)
The .NET Framework is good at managing connections. While you're opening and closing them in your code, behind the scenes it's actually keeping connections open for a brief period. This is called thread pooling. When you close a connection, it's actually kept open temporarily. When you open a new connection, it might actually give you the same one.
Most of the time we don't need to pay attention to that. All we do is create a new connection as close as possible to when we're going to open and use it, and then close (dispose) it as soon as possible.

blank mysql insert into database

hi i created a private sub where the code must insert a mysql command.... and it does but the funnyest part is that the record disapeares from database
it's there but ehn i stop the debbug and start over it is not there , not even in database
why?
Private Sub gravarAtleta()
Dim sqlStatement = "insert into atl([nome],[morada],[sexo],[datan],[telf],[desporto]) "
sqlStatement &= "VALUES (#nome, #morada, #sexo, #datan, #telf, #desporto)"
Using xConn As New SqlConnection(myConnectionString)
Try
Dim xComm As New SqlCommand(sqlStatement, xConn)
With xComm
.CommandType = CommandType.Text
.Parameters.AddWithValue("#nome", txtNome.Text)
.Parameters.AddWithValue("#morada", txtMorada.Text)
.Parameters.AddWithValue("#sexo", ComboSexo.Text)
.Parameters.AddWithValue("#datan", CType(txtDataN.Text, DateTime).ToString("yyyy-MM-dd"))
.Parameters.AddWithValue("#telf", txtTelemovel.Text)
.Parameters.AddWithValue("#desporto", ComboBox1.Text)
End With
xConn.Open()
xComm.ExecuteNonQuery()
xComm.Dispose()
Label1.Content = "O atleta " + txtNome.Text + " foi registado!!!"
Catch ex As SqlException
MsgBox(ex.Message)
Label1.Content = "Falhou a ligação a base de dados!!!"
End Try
End Using
End Sub
Ive modified the code see if it works
Private Sub gravarAtleta()
Dim sqlStatement = "INSERT INTO atl([nome],[morada],[sexo],[datan],[telf],[desporto]) "
sqlStatement &= "VALUES (#nome, #morada, #sexo, #datan, #telf, #desporto)"
Using xConn As New SqlConnection(myConnectionString)
Using xComm As New SqlCommand(sqlStatement, xConn)
With xComm
.CommandType = CommandType.Text
.Parameters.AddWithValue("#nome", txtNome.Text)
.Parameters.AddWithValue("#morada", txtMorada.Text)
.Parameters.AddWithValue("#sexo", ComboSexo.Text)
.Parameters.AddWithValue("#datan", CType(txtDataN.Text, DateTime).ToString("yyyy-MM-dd"))
.Parameters.AddWithValue("#telf", txtTelemovel.Text)
.Parameters.AddWithValue("#desporto", ComboBox1.Text)
End With
Try
xConn.Open
xComm.ExecuteNonQuery
Label1.Content = "O atleta " + txtNome.Text + " foi registado!!!"
Catch ex As SqlException
Msgbox (ex.Message)
Label1.Content = "Falhou a ligação a base de dados!!!"
Finally
xConn.Close
End Try
End Using
End Using
End Sub
First, your command creation should be done with a using statement; that way you won't have to have the dispose statement and the object will be disposed even if the database generates and exception. For example:
Using xComm As New SqlCommand(sqlStatement, xConn)
With xComm
.CommandType = CommandType.Text
.Parameters.AddWithValue("#nome", txtNome.Text)
.Parameters.AddWithValue("#morada", txtMorada.Text)
.Parameters.AddWithValue("#sexo", ComboSexo.Text)
.Parameters.AddWithValue("#datan", CType(txtDataN.Text, DateTime).ToString("yyyy-MM-dd"))
.Parameters.AddWithValue("#telf", txtTelemovel.Text)
.Parameters.AddWithValue("#desporto", ComboBox1.Text)
xConn.Open()
.ExecuteNonQuery()
End With
End Using
Second, are you perhaps including the database in the deployment for your app? I'm not even sure this is possible using MySQL, but we have run into issues like this before where we include a copy of the database (SQLCE, Access) as content in the solution and have it copy to the output directory on build.
This causes great confusion because the changes that were made during previous debug cycles are overwritten by the newly copied database.