blank mysql insert into database - mysql

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.

Related

how can i add a DateTimePicker and ComboBoxes to mysql database then displaying it to DataGridView

Form
Sub ViewRecords()
Try
read("SELECT * FROM reservation", DataGridView1)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub add_Click(sender As Object, e As EventArgs) Handles add.Click
Try
ComboTIME = (hr.SelectedItem.ToString + ":" + min.SelectedItem.ToString + " " + fr.SelectedItem.ToString)
write("INSERT INTO reservation (ReservationCode, UserId, RestaurantName, RestaurantLocation, Time, Date, ReservationStatus, Remarks) VALUES ('" & code.Text & "','" & userid.Text & "','" & restoname.Text & "', '" & restolocation.Text & "', '" & datepicker.Value & "', '" & ComboTIME & "', '" & ans & "', '" & remarks.Text & "')")
code.Clear()
userid.Clear()
restoname.Clear()
restolocation.Clear()
datepicker.ResetText()
hr.ResetText()
min.ResetText()
fr.ResetText()
y.ResetText()
n.ResetText()
remarks.Clear()
ViewRecords()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
MODULE CONNECTION
Public Sub read(ByVal sql As String, ByVal DTG As Object)
Try
dt = New DataTable
con.Open()
With cmd
.Connection = con
.CommandText = sql
End With
da.SelectCommand = cmd
da.Fill(dt)
DTG.DataSource = dt
Catch ex As Exception
MessageBox.Show(ex.Message & ex.Source, "Load Data Failed")
con.Close()
End Try
con.Close()
da.Dispose()
End Sub
Public Sub write(ByVal sql As String)
Try
con.Open()
With cmd
.Connection = con
.CommandText = sql
result = cmd.ExecuteNonQuery
If result = 0 Then
MessageBox.Show("FAILED.")
Else
MessageBox.Show("SUCCESS.")
End If
End With
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
con.Close()
End Sub
My only problem in my program is that when i click the button the datetimepicker and the comboboxes that i bind and declared as ComboTIME wont record in the database and also in the datagridview, My connection with the database is fine and the TextBoxes were storable and displayable in both database and datagridview, can anyone help me with this problem?
Always provide accessibility modifiers to make your code clearer to read. When you start working in multimple languages in multiple evironments it might be difficult to remember whai the default accessibility is in vb.net.
Separate you data access code from your user interface code. For example, you are passing a DataGridView to your module code. Suppose the boss says he really wants to have a web app. Now you not only have to fix your user interface code but you need to modify your module too. Keeping them separate would only require changing the UI code. My DataAccess class remains the same.
Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
Parameters help protect against sql injection. A user can enter anything in a text box including "Delete * From reservation" Parameters provide only values not executable code so they cannot damage the database. I had to guess at the SqlDbType so, you need to check you database for the correct types.
User Interface code...
Private Sub ViewRecords()
Dim dt As DataTable = Nothing
Try
dt = DataAccess.GetReservationData
Catch ex As Exception
MsgBox($"Failed to fill grid {ex.Message}")
Return
End Try
DataGridView1.DataSource = dt
End Sub
Private ans As String = ""
Private Sub InsertReservation()
Dim code As Integer
If Not Integer.TryParse(code.Text, code) Then
MessageBox.Show("Code needs to be a number.")
Return
End If
Dim userID As Integer
If Not Integer.TryParse(userid.Text, userID) Then
MessageBox.Show("User ID needs to be a number.")
Return
End If
Try
DataAccess.InsertReservation(code, userID, restoname.Text, restolocation.Text, ComboTIME.Text, datepicker.Value, ans, remarks.Text)
Catch ex As Exception
MessageBox.Show($"Insert Failed {ex.Message}")
Return
End Try
MessageBox.Show("Reservation inserted successfully.")
End Sub
Database code...
Public Class DataAccess
Private Shared ConStr As String = "Your connection string"
Public Shared Function GetReservationData() As DataTable
Dim dt As New DataTable
Using con As New MySqlConnection(ConStr),
cmd As New MySqlCommand("SELECT * FROM reservation", con)
con.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Public Shared Sub InsertReservation(ReservationCode As Integer, UserID As Integer, RestaurantName As String, Location As String, Time As String, ResDate As Date, Status As String, Remarks As String)
Using con As New MySqlConnection(ConStr),
cmd As New MySqlCommand("INSERT INTO reservation (ReservationCode, UserId, RestaurantName, RestaurantLocation, Time, Date, ReservationStatus, Remarks) VALUES (#ResurvationCode, #UserID, #RestaurantName, #Location, #Time, #Date, #Status, #Remarks)", con)
With cmd.Parameters
.Add("#ReservationCode", MySqlDbType.Int32).Value = ReservationCode
.Add("#UserID", MySqlDbType.Int32).Value = UserID
.Add("#RestaurantName", MySqlDbType.VarChar).Value = RestaurantName
.Add("#Location", MySqlDbType.VarChar).Value = Location
.Add("#Time", MySqlDbType.VarChar).Value = Time
.Add("#Date", MySqlDbType.DateTime).Value = ResDate
.Add("#Status", MySqlDbType.VarChar).Value = Status
.Add("#Remarks", MySqlDbType.VarChar).Value = Remarks
End With
End Using
End Sub
End Class

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

Updating MYSQL records via VB.NET

What I am trying to do is do the basic insert, refresh and update mysql querys in my vb.net application. The refresh, and the insert work perfect the only one I can't get is the update can anyone tell me what I am doing wrong? Here is a picture of the program layout:
http://i.imgur.com/mHxKGrb.png
and here is my source code:
Private Sub KnightButton3_Click(sender As Object, e As EventArgs) Handles KnightButton3.Click
cn = New MySqlConnection
cn.ConnectionString = "my info"
Try
cn.Open()
Dim query As String
Dim command As MySqlCommand
query = "UPDATE Refers.exploitsociety SET Refferals='" + refupdate.Text + "' WHERE Refferals='" + DataGridView1.CurrentCell.Selected + "';"
command = New MySqlCommand(query, cn)
cmd.ExecuteNonQuery()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
cn.Dispose()
End Try
cn.Close()
End Sub
I think your problem is in the usage of the property Selected of the CurrentCell. This is a boolean value and it is not the content of that cell.
I would use this kind of code with a parameterized query and a using statement around disposable objects
Try
query = "UPDATE Refers.exploitsociety " & _
"SET Refferals=#refs " & _
"WHERE Refferals=#oldrefs"
Using cn = New MySqlConnection(".... connection string ....")
Using command = New MySqlCommand(query, cn)
cn.Open()
command.Parameters.Add("#refs", MySqlDbType.Int32).Value = _
Convert.ToInt32(refupdate.Text)
command.Parameters.Add("#oldrefs", MySqlDbType.Int32).Value = _
Convert.ToInt32(DataGridView1.CurrentCell.Value.ToString())
command.ExecuteNonQuery()
End Using
End Using
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
Notice that with a using statement you don't need to close/dispose the connection because this is automatically done when the code leaves the using block (also in case of exceptions)

vb net max_user_connections to 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)

Visual Basic 2010 and Mysql Nested Query

I'm using VB2010 Express, I've got a Mysql tablet with the following Fields Ext, CostAssing and CostAct, I'm trying to update a Mysql table from the result got in a first query:
First query Get Ext and CostAssing
Second Query Update field CostAct with CostAssing value
**
Imports MySql.Data.MySqlClient
Imports System
Imports System.IO
Public Class Form1
Public dbconn As New MySqlConnection
Public sql As String
Public sqlQuery As String
Public SQLcmd As MySqlCommand
Public dbcomm As MySqlCommand
Public dbread As MySqlDataReader
Dim Ext As String
Dim CostAssing As Integer
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
dbconn = New MySqlConnection("Data Source=localhost ; user id=root ; password=password ; database=calls")
'First Query Get Extension and CostAssing
Try
dbconn.Open()
sqlQuery = "SELECT Ext,CostAssing FROM estruc "
SQLcmd = New MySqlCommand(sqlQuery, dbconn)
dbread = SQLcmd.ExecuteReader
While dbread.Read()
Ext = dbread.Item("Ext")
CostAssing = dbread.Item("CostAssing")
MsgBox("Ext:" & Ext)
'Second Query Update Ext from CostAct to CostAssing
Try
sqlQuery = "UPDATE estruc SET CostAct = '" & "1000" & "' WHERE Ext = '" & Ext & "'"
SQLcmd = New MySqlCommand(sqlQuery, dbconn)
dbread = SQLcmd.ExecuteReader
Catch ex As Exception
MsgBox("Error 2 is :" & ex.Message)
End Try
End While
Catch ex As Exception
MsgBox("Error 1 is :" & ex.Message)
End Try
dbread.Close()
End Sub
End Class
**
The first query run ok, I get fields Ext and CostAssing, But When the second Query try to Update de field CostAct I get following error (Reported by Catch ex As Exception MsgBox("Error 2 is :" & ex.Message)):
"Error 2 is: There is already an open Datareader associated with this Connection which must be closed first."
PLease, Any Ideas?
Add the following line to close the datareader after the first query
dbread.Close();
You'll want to store the values from dbread first (datatable or list, etc), close the while loop, then run the second query with:
SQLcmd.ExecuteNonQuery();
Please see this similar question