INSERT More than 50 Query Using same opened connection - mysql

So what i basically want is to insert more than 1 query to my database without needing of conn.close than conn.open too many times and also doing try more than 50 times ..
Here is exp for the code :
Dim COMMAND As MySqlCommand
Dim reader As MySqlDataReader
Dim conn As MySqlConnection
Dim Item1 As String = "INSERT INTO item_template (entry, name, display) VALUES ('1234', 'Testing', '654';"
Dim Item3 As String = "UPDATE Item_template SET entry = '123' where name like 'test32111';"
Dim Item2 As String = "INSERT INTO item_template (entry, name, display) VALUES ('123467', 'Testing332', '65478';"
Try
conn.Open()
COMMAND = New MySqlCommand(Item1, conn)
reader = COMMAND.ExecuteReader
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Try
conn.Open()
COMMAND = New MySqlCommand(Item3, conn)
reader = COMMAND.ExecuteReader
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Try
conn.Open()
COMMAND = New MySqlCommand(Item2, conn)
reader = COMMAND.ExecuteReader
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

Without addressing other matters like parameterized/prepared queries, the simplest fix should be...
Dim COMMAND As MySqlCommand
Dim conn As MySqlConnection
Dim Item1 As String = "INSERT INTO item_template (entry, name, display) VALUES ('1234', 'Testing', '654');"
Dim Item3 As String = "UPDATE Item_template SET entry = '123' where name like 'test32111';"
Dim Item2 As String = "INSERT INTO item_template (entry, name, display) VALUES ('123467', 'Testing332', '65478');"
Try
conn.Open()
COMMAND = New MySqlCommand("", conn)
COMMAND.CommandText = Item1
COMMAND.ExecuteNonQuery
COMMAND.CommandText = Item2
COMMAND.ExecuteNonQuery
COMMAND.CommandText = Item3
COMMAND.ExecuteNonQuery
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
My VB is a little rusty though, so beware of typo-level errors (I tried to add ; more than once)

There are some optimizations you can make. You should embed the disposable resources in a Using-Statement. The Using statement automatically closes and disposes the resources at the end. Especially the connection will be closed automatically. It does so, even if the Using-block is left prematurely because of an exception or because a Return statement terminates the method.
Keep the connection open while processing the batch.
DRY: Don't Repeat Yourself. Try to avoid code repetition make with copy paste. In the following example I create an array of SQL texts that can be processed in a loop.
SQL commands like INSERT, UPDATE, DELETE do not return a result set. Use ExecuteNonQuery instead of ExecuteReader for them.
The command can be resued by assigning it a new command text.
Dim sqlTexts = {
"INSERT INTO item_template (entry, name, display) VALUES ('1234', 'Testing', '654';",
"UPDATE Item_template SET entry = '123' where name like 'test32111';",
"INSERT INTO item_template (entry, name, display) VALUES ('12367', 'Testing332', '65478';"
}
Using _
conn As New MySqlConnection(connectionString),
command As New MySqlCommand With {
.CommandType = CommandType.Text,
.Connection = conn
}
conn.Open()
For Each sql As String In sqlTexts
Try
command.CommandText = sql
command.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Next
End Using
Note that the Using-statement includes the command as well as we are using VB's Implicit Line Continuation feature as for the initialization of the sqlTexts array.

Related

Hide part of String.Format within a ComboBox.Item

Is it possible to hide part of String.Format?
This my code:
'Select Product'
Try
MysqlConn.Close()
MysqlConn.Open()
Dim Query As String
Query = "select id, name,id_maker, id_types from product ORDER BY name ASC"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Dim sName = READER.GetString("name")
Dim sMaker = READER.GetString("id_maker")
Dim sTypes = READER.GetString("id_types")
Dim sId = READER.GetString("id")
'ComboBox1.Items.Add(sName)'
ComboBox1.Items.Add(String.Format("{0}|{1}|{2}|{3}", sName, sMaker, sTypes, sId))
End While
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
'Select Product'
I want to hide {3} which is sId in the ComboBox, because later I need to use a query where the ComboBox1.Text is used and the id is necessary.
Maybe you could change the way you are assigning the data to the ComboBox.
First thing to do is change the query and use CONCAT:
SELECT id, CONCAT(name,'|',id_maker,'|',id_types) AS value FROM product ORDER BY name ASC
I would also implement Using:
Managed resources are disposed of by the .NET Framework garbage collector (GC) without any extra coding on your part. You do not need a Using block for managed resources. However, you can still use a Using block to force the disposal of a managed resource instead of waiting for the garbage collector.
You also don't need the READER. Instead load the data into a DataTable and assign that to the .DataSource property on the ComboBox.
Your code would look something like this:
Using con As New MySqlConnection(connectionString)
cmd As New MySqlCommand("SELECT id, CONCAT(name,'|',id_maker,'|',id_types) AS value FROM product ORDER BY name ASC", con)
con.Open()
Dim dt As New DataTable
dt.Load(cmd.ExecuteReader())
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "value"
ComboBox1.ValueMember = "id"
End Using
You can now get the id with this bit of code:
ComboBox1.SelectedValue.ToString()
And you can get the text with this bit of code:
ComboBox1.Text
Ok i use now that and works
Dim connetionString As String = Nothing
Dim connection As MySqlConnection
Dim command As MySqlCommand
Dim adapter As New MySqlDataAdapter()
Dim ds As New DataSet()
Dim i As Integer = 0
Dim sql As String = Nothing
'connetionString = "Data Source=ServerName;Initial Catalog=databasename;User ID=userid;Password=yourpassword"
'sql = "select id,name from product"
sql = "SELECT id, CONCAT(name,' | ',id_maker,' | ',id_types) AS value FROM product ORDER BY name ASC"
'connection = New MySqlConnection(connetionString)
connection = New MySqlConnection(ConfigurationManager.ConnectionStrings("xCollectibles.My.MySettings.xcollectiblesConnectionString").ToString)
Try
connection.Open()
command = New MySqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
connection.Close()
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.ValueMember = "id"
ComboBox1.DisplayMember = "value"
Catch ex As Exception
MessageBox.Show("Can not open connection ! ")
End Try
Thanks you..

How do I catch MySQL errors in a try catch block?

I am trying to execute a query on a MySQL database. I've put the execute command in a try catch block, but It still throws an exception when the query fails. How do I prevent this and simply catch the error?
Dim db_connection As String = my_connection_string
Dim MyConn As OdbcConnection
MyConn = New OdbcConnection(db_connection)
Dim MyCommand As New OdbcCommand()
Dim myReader As OdbcDataReader = Nothing
MyCommand.Connection = MyConn
MyConn.Open()
query = "Alter table Table1 ADD COLUMN `col_2` VARCHAR(50) AFTER `col_1`"
MyCommand.CommandText = query
try
myReader = MyCommand.ExecuteReader()
catch ex as Exception
output(ex.tostring)
end try
myReader.Close()
If the column already exists, it throws an error but if it does not, then everything is fine and the query gets executed and the program go on.
If you are going to catch an exception, you should catch the whole code of the query because, the connection can fail as well for instance.
Dim db_connection As String = my_connection_string
Dim MyConn As OdbcConnection
Dim MyCommand As New OdbcCommand()
try
MyConn = New OdbcConnection(db_connection)
MyCommand.Connection = MyConn
MyConn.Open()
query = "Alter table Table1 ADD COLUMN `col_2` VARCHAR(50) AFTER `col_1`"
MyCommand.CommandText = query
MyCommand.ExecuteNonQuery()
catch ex as Exception
output(ex.tostring)
end try
EDIT:
Try
Using connection As New OdbcConnection(my_connection_string)
query = "Alter table Table1 ADD COLUMN `col_2` VARCHAR(50) AFTER `col_1`"
Using command As New OdbcCommand(query, connection)
connection.Open()
command.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
EDIT
Try
'code here
Catch exception As OdbcException
Console.WriteLine(exception.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try

SELECT MAX(value) from table VB.net

I have this table that contains multiple values all ranging from 1 to 3000, but it keep retuning false.
What is going wrong here?
Dim connectionString As String = "Server=**; Uid=**; Pwd=**; Database=**"
Using SQLConnection As New MySqlConnection(connectionString)
Using sqlCommand As New MySqlCommand()
With sqlCommand
.CommandText = "SELECT MAX(CAST(points AS UNSIGNED)) FROM score"
.Connection = SQLConnection
.CommandType = CommandType.Text
End With
Try
SQLConnection.Open()
Using reader As MySqlDataReader = sqlCommand.ExecuteReader
While (reader.Read())
label1.Text = reader.Read()
End While
End Using
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
End Using
End Using
Probably you need to read the field not calling again Read
label1.Text = reader(0).ToString()
However, to read a scalar value like you do, it is preferable to use the ExecuteScalar method. It returns just the single value of your query without creating an MySqlDataReader and all the infrastructure needed when you want to read more than one record one by one
Using sqlCommand As New MySqlCommand()
With sqlCommand
.CommandText = "SELECT MAX(CAST(points AS UNSIGNED)) FROM score"
.Connection = SQLConnection
.CommandType = CommandType.Text
End With
Try
SQLConnection.Open()
Dim result = Convert.ToInt64(sqlCommand.ExecuteScalar())
label1.Text = result.ToString()
.....
Read() advances to the next row/result (and returns a boolean indicating if you've passed the end of the result set); you're looking for GetInt32() or similar methods.

Can't save info to mysql database

I'm trying to store info to a mysql database, but for some reason it's not working for me.
Dim connString As String = "server=sql3.freemysqlhosting.net; userid=Censored;password=Censored;database=sql364455"
Dim conn As New MySqlConnection(connString)
Dim cmd As New MySqlCommand()
Try
conn.Open()
cmd.Connection = conn
cmd.CommandText = "INSERT INTO accounts (`user_num`, `username`, `password`) values (#1,#2,#3)"
MsgBox("1")
cmd.Parameters.AddWithValue("#1", TextBox1.Text)
cmd.Parameters.AddWithValue("#2", TextBox2.Text)
cmd.Parameters.AddWithValue("#3", TextBox3.Text)
MsgBox("2")
cmd.ExecuteNonQuery()
MsgBox("3")
MessageBox.Show("User Profile Created!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
conn.Close()
Catch ex As Exception
End Try
According to this code the message boxes 1 and 2 is popping up but 3 is not.
Any idea? thanks in advance.
#WoeIsMe Plutonix already told you how to write it correctly (put it into brackets: [password]). And, just and advice; if you're already using MsgBox as a debugging tool, always put another one inside the catch block with the exception MsgBox(ex.ToString()), so you'll know why it is not working. – Josh Part 8
I've put a msgbox on the exception block to find out what is the problem and I found that it didn't worked because: "Duplicate entry '0' for key 'PRIMARY' " - it didn't worked because there was already a user with this number.
thanks alot for all the people who helped me.
the code I used to detect the problem:
Dim connString As String = "server=sql3.freemysqlhosting.net; userid=username;password=password;database=sql364455"
Dim conn As New MySqlConnection(connString)
Dim cmd As New MySqlCommand()
Try
conn.Open()
cmd.Connection = conn
cmd.CommandText = "INSERT INTO accounts (user_num, username, password) values (#1,#2,#3)"
MsgBox("1")
cmd.Parameters.AddWithValue("#1", TextBox1.Text)
cmd.Parameters.AddWithValue("#2", TextBox2.Text)
cmd.Parameters.AddWithValue("#3", TextBox3.Text)
MsgBox("2")
cmd.ExecuteNonQuery()
MsgBox("3")
MessageBox.Show("User Profile Created!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
conn.Close()
Catch ex As Exception
' here
MsgBox(ex.Message)
End Try

vb.net/mysql show more then 1 row in TextBox

I just started messing around with Visual basic (vb.net) and am trying to show more then 1 database row in a TextBox, so far I have this:
Private Sub foobox_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString = connStr
Try
conn.Open()
Catch myerror As MySqlException
MsgBox("No connection")
End Try
Dim myAdaptor As New MySqlDataAdapter
Dim sqlquery = "SELECT * FROM foo ORDER BY id DESC"
Dim myCommand As New MySqlCommand()
myCommand.Connection = conn
myCommand.CommandText = sqlquery
myAdaptor.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader()
If myData.HasRows Then
myData.Read()
Viewer.Text = myData("foo1") & myData("foo2")
End If
myData.Close()
conn.Close()
End Sub
which connects to a database successfully but but it only outputs 1 row, how can I get it to output more?
You need a loop reading data and storing line after line in a StringBuilder.
Then, when exiting from the reading loop set the Text property of your textbox
Dim sb as StringBuilder = new StringBuilder()
While myData.Read()
sb.AppendLine(myData("foo1") & myData("foo2"))
End While
Viewer.Text = sb.ToString
and, of course, your textbox should have the MultiLine property set to True
Apart from this direct answer to your question, your code should be changed to dispose the connection and the datareader after use, I have also removed the DataAdapter because is not needed here
Using conn = New MySqlConnection(connStr)
Try
conn.Open()
Catch myerror As MySqlException
MsgBox("No connection")
End Try
Dim sqlquery = "SELECT * FROM foo ORDER BY id DESC"
Dim myCommand As New SqlCommand(sqlquery, conn)
Using myData = myCommand.ExecuteReader()
Dim sb as StringBuilder = new StringBuilder()
While myData.Read()
sb.AppendLine(myData("foo1") & myData("foo2"))
End While
Viewer.Text = sb.ToString
End Using
End Using
You need some kind of loop. I would also use the Using statement to ensure that all unmanaged resources are disposed even in case of an exception(it also closes the connection):
Using conn As New MySqlConnection(connStr)
Using myCommand As New MySqlCommand("SELECT * FROM foo ORDER BY id DESC", conn)
Try
conn.Open()
Using myData = myCommand.ExecuteReader()
If myData.HasRows Then
While myData.Read()
Dim line = String.Format("{0}{1}{2}",
myData.GetString(myData.GetOrdinal("foo1")),
myData.GetString(myData.GetOrdinal("foo1")),
Environment.NewLine)
viewer.Text &= line
End While
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Using
End Using
However, if you want to show multiple records i would recommend a ListBox instead. It's more efficient with many items and it also separates them logical from each other.
( just replace viewer.Text &= line with ListBox1.Items.Add(line) )