MYSQL connection string in old VB.NET project in Access - mysql

I have a very old project that uses an Access DB (.mdb) and uses various connections from various pages. Some include OLE DB, DAO, ADO. I have over 200 pages with various connections. I'm moving over to MySQL and want to cleanup this mess. Starting with OLEDB I'm having trouble with a connection that will allow me to keep the rest of my code (or even if it can be done?)
Yes I have looked at the various examples in: http://www.connectionstrings.com/net-framework-data-provider-for-ole-db/
Here is one of the many pages I need to move to MySQL connection:
Partial Class mysql_a_Checkoff
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click, Button1.DataBinding
'*** Code to insert class checkoff into class_record table ***
For index As Integer = 0 To GridView1.Rows.Count - 1
'Programmatically access the Checkbox from the TemplateField
Dim cb As CheckBox = CType(GridView1.Rows(index).FindControl("RowLevelCheckBox"), CheckBox)
'If it is checked, insert it into class records table
If cb.Checked Then
'Code to insert into DB table
Dim FDID As String = GridView1.Rows(index).Cells(1).Text.ToString
Dim Instructor As String = User.Identity.Name()
Dim DateCompleted As Date = TextBox1.Text
Dim Completed As Boolean = True
Dim Enrolled As Boolean = False
Dim UserName As String = GridView1.Rows(index).Cells(4).Text.ToString
Dim ClassName As String = DropDownList1.SelectedValue.ToString
Dim ClassDate As Date = CDate(TextBox1.Text)
Dim WaitListed As Boolean = False
Dim Walkin As Boolean = False
response.write("Yes - ")
InsertClassRecord(UserName, Instructor, DateCompleted, Completed, Enrolled, ClassName, ClassDate, WaitListed, Walkin)
End If
Next
Response.Redirect("i_toc.aspx")
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
TextBox1.Text = Now.Date
End If
End Sub
Public Function InsertClassRecord(ByVal UserName As String, ByVal Instructor As String, _
ByVal DateCompleted As Date, ByVal Completed As Boolean, _
ByVal Enrolled As Boolean, ByVal ClassName As String, _
ByVal ClassDate As Date, ByVal WaitListed As Boolean, _
ByVal Walkin As Boolean) As Object
Dim connStr As String = "Provider=SQLOLEDB;Server=localhost;Database=mysql_training;Uid=myUsr;Pwd=myPwd;"
conn.ConnectionString = connStr
conn.Open()
Dim sql As String = "INSERT INTO EnrollmentsTbl (" & _
"[UserName],[SubmitTime],[ClassTime],[ClassDate],[Enrolled],[ClassName],[WaitListed]," & _
"[Instructor],[DateCompleted],[Completed],[Walkin]) VALUES " & _
"(#UserName, #SubmitTime, #ClassTime, #ClassDate, #Enrolled, #ClassName, #WaitListed, " & _
"#Instructor, #DateCompleted, #Completed, #Walkin) "
Dim comm As New Data.OleDb.OleDbCommand(sql, conn)
comm.Parameters.AddWithValue("#UserName", UserName)
comm.Parameters.AddWithValue("#SubmitTime", DateTime.Now.ToString())
comm.Parameters.AddWithValue("#ClassTime", "0800")
comm.Parameters.AddWithValue("#ClassDate", ClassDate)
comm.Parameters.AddWithValue("#Enrolled", Enrolled)
comm.Parameters.AddWithValue("#ClassName", ClassName)
comm.Parameters.AddWithValue("#WaitListed", WaitListed)
comm.Parameters.AddWithValue("#Instructor", Instructor)
comm.Parameters.AddWithValue("#DateCompleted", DateCompleted)
comm.Parameters.AddWithValue("#Completed", Completed)
comm.Parameters.AddWithValue("#Walkin", Walkin)
Dim result As Integer = comm.ExecuteNonQuery()
conn.Close()
Return True
End Function
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
e.Row.Cells(4).Visible = False
End Sub
End Class

Not sure I fully understand the question, but I'll take a stab at it.
Download the MySQL NET Connector and add a reference to your project. Any place where you are using a OleDBConnection or OleDBCommand you will need to change that to MySqlConnection and MySqlCommand respectively. This should allow you to reuse you existing logic as much as possible.
For example, in your InsertClassRecord method you would change this
Dim comm As New Data.OleDb.OleDbCommand(sql, conn)
to this
Dim comm As New MySqlCommand(sql, conn)
And you should be able to keep the existing logic

Related

Visual Basic connect database with ODBC setting with register

I have the code written to connect to the ODBC registry.
The database name is written to the combobox.
I need to transfer my ip address and password from ODBC.ini to the connect string after selecting the database from the combobox.
This is a connection to MYSQL.
Thank you
Private Sub DsnLookup()
Dim dsnNames As New List(Of String)
Dim reg As Microsoft.Win32.RegistryKey = Registry.CurrentUser.OpenSubKey("Software")
If reg IsNot Nothing Then
reg = reg.OpenSubKey("ODBC")
If reg IsNot Nothing Then
reg = reg.OpenSubKey("ODBC.INI")
If reg IsNot Nothing Then
For Each dsn As String In reg.GetSubKeyNames
dsnNames.Add(dsn)
Next
End If
End If
End If
For Each Name As String In dsnNames
ComboBox1.Items.Add(Name)
Next Name
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DsnLookup()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connString As String = "Database='combobox data;Data Source='ip adres odbc;" _
& "User Id=root;Password=' odbc PWD"
You can get the Server Name (or IP) and Database name from the ODBC.INI but it doesn't store the password. Either include a master password in your connectionstring (securely of course) or look into other authentication options.
This is how to get the Database and Server info from the registry. Keeping your code the same, but replacing the Button1.Click event and adding an additional function:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ComboBox1.SelectedIndex >= 0 Then 'Make sure something from dropdown selected
Dim connString As String = String.Format("Database='{0}';Data Source='{1}';User Id=root;", GetODBCValue(ComboBox1.SelectedItem, "Database"), GetODBCValue(ComboBox1.SelectedItem, "Server"))
End If
End Sub
Private Function GetODBCValue(ByVal ODBCName As String, ByVal ValueName As String) As String
Dim reg As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software")
reg = reg.OpenSubKey("ODBC")
reg = reg.OpenSubKey("ODBC.INI")
reg = reg.OpenSubKey(ODBCName)
Return reg.GetValue(ValueName)
End Function
thank you for the answer
I tried to edit it
Private Function GetODBCValu(ByVal ODBCName As String, ByVal ValueName As String) As String
Dim dsnNames As New List(Of String)
Dim reg As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software")
reg = reg.OpenSubKey("ODBC")
reg = reg.OpenSubKey("ODBC.INI")
reg = reg.OpenSubKey(ODBCName)
Return reg.GetValue(ValueName)
For Each dsn As String In reg.GetSubKeyNames
dsnNames.Add(dsn)
Next
For Each Name As String In dsnNames
ComboBox1.Items.Add(Name)
Next Name
End Function
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim connString As String = String.Format("Database='{0}';Data Source='{1}';User Id=root;", GetODBCValu(ComboBox1.SelectedItem, "Database"), GetODBCValu(ComboBox1.SelectedItem, "Server"))
Dim conn As New MySqlConnection(connString)
Dim cmd As New MySqlCommand()
Try
Call conecDB()
dt = New DataTable 's_table
Dim con As New SqlConnection
DateTimePicker1.CustomFormat = "yyyy-MM-dd"
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker2.CustomFormat = "yyyy-MM-dd"
DateTimePicker2.Format = DateTimePickerFormat.Custom
conn.Open()
cmd.Connection = conn
da = New MySql.Data.MySqlClient.MySqlDataAdapter("select --- ", connDB)
comBuilderDB = New MySql.Data.MySqlClient.MySqlCommandBuilder(da)
da.Fill(dt)
dbvypis.DataSource = dt
conn.Close()
MessageBox.Show("COMPLET")
Catch ex As MySqlException
Console.WriteLine("Error: " & ex.ToString())
End Try
Try
'declaring variable as integer to store the value of the total rows in the datagridview
Dim max As Integer = dbvypis.Rows.Count - 1
Dim total As String = "TOTAL ----->"
Dim TOTALCOST As Integer = 0
'getting the values of a specific rows
For Each row As DataGridViewRow In dbvypis.Rows
'formula for adding the values in the rows
TOTALCOST += row.Cells(1).Value
Next
dbvypis.Rows(max).Cells(1).Value += TOTALCOST
dbvypis.Rows(max).Cells(0).Value = total
Catch ex As Exception
MsgBox(ex.Message)
End Try
It occurred to me that if I select a database in the comboboxu so it gets into ODBC and connString to the command adds the server and database name
Then it writes to me in the result Index is out of range, Index must be non-negative and must be smaller than the collection size. Parameter name: index

how insert data to server on client with database mysql with background worker vb.net?

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
koneksiserver()
Try
Dim sqlinsert As String = "INSERT INTO sentitems (TextDecoded, " & _
"DestinationNumber,SenderID,ID)" & _
"VALUES(#isi,#nohp,#modem,#ID)"
Dim cmd = New MySqlCommand(sqlinsert, MyCon)
cmd.Parameters.Add("#isi", MySqlDbType.Text)
cmd.Parameters.Add("#nohp", MySqlDbType.VarChar)
cmd.Parameters.Add("#modem", MySqlDbType.VarChar)
cmd.Parameters.Add("#ID", MySqlDbType.Int16)
For i As Integer = 0 To DataGridView3.Rows.Count - 0
cmd.Parameters("#isi").Value = DataGridView3.Rows(i).Cells(1).Value
cmd.Parameters("#nohp").Value = DataGridView3.Rows(i).Cells(3).Value
cmd.Parameters("#modem").Value = DataGridView3.Rows(i).Cells(4).Value
cmd.Parameters("#ID").Value = DataGridView3.Rows(i).Cells(6).Value
cmd.ExecuteNonQuery()
Next
DisplayStatus("Conected...")
isExecuting = True
Dim callback As New AsyncCallback(AddressOf HandleCallback)
cmd.BeginExecuteNonQuery(callback, cmd)
MyCon.Close()
Catch ex As Exception
'MyCon.Close()
' MsgBox("Export Berhasil", MsgBoxStyle.Exclamation, "DHAPU SMS")
End Try
End Sub
Private Sub set_db_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles set_db.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Azmy;
Assuming that you are using a BackgroundWorker to prevent UI lockup:
You can not reference any objects tied to the UI thread, referring to DataGridView3, DisplayStatus and MsgBox are guaranteed exceptions.
Also your loop
For i As Integer = 0 To DataGridView3.Rows.Count - 0
will fail because you are not adjusting the count properly use a -1 not a minus 0
To accomplish what you want you must pass a table object or an array of data objects or what ever data you want updated through the System.ComponentModel.DoWorkEventArgs argument.

mysql, vb.net - Saving Transaction not working

I don't know what's the real problem since there are no error being reported. So what I want these codes to do is insert a transaction record to the database but there is nothing being returned. Here are the codes that related to this:
MainForm
Private Sub PayButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PayButton.Click
Dim payment As New Payment
payment.Show()
AddHandler payment.PaymentEvent, AddressOf paymentSuccess
payment.PaymentAmount = TransactionTotal
End Sub
Public Sub paymentSuccess(ByVal sender As Object, ByVal e As Payment.PaymentMadeEventArgs)
mydbcon = New MySqlConnection
mydbcon.ConnectionString = "server=localhost;userid=root;password=;database=sdudb"
Dim reader As MySqlDataReader
Try
mydbcon.Open()
Dim Query As String
Query = "select * from inventory"
COMMAND = New MySqlCommand(Query, mydbcon)
reader = COMMAND.ExecuteReader()
While reader.Read
Dim itId As Integer = reader.GetString("itemid")
Dim itName As String = reader.GetString("itemname")
If e.PaymentSuccess = True Then
paymentSuccessQuery(itId, itName)
End If
End While
reader.Close()
mydbcon.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub paymentSuccessQuery(ByVal itemid, ByVal itemname)
mydbcon = New MySqlConnection
mydbcon.ConnectionString = "server=localhost;userid=root;password=;database=sdudb"
Dim reader As MySqlDataReader
Try
mydbcon.Open()
Dim Query As String
Query = "INSERT INTO transaction (itemid, itemname) VALUES('" & itemid & "', '" & itemname & "')"
COMMAND = New MySqlCommand(Query, mydbcon)
reader = COMMAND.ExecuteReader()
If reader.Read Then
MessageBox.Show("Unable to save transaction!")
Else
MessageBox.Show("Transaction Saved!")
End If
reader.Close()
mydbcon.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Transactionform
Public Class Payment
Public Delegate Sub PaymentMadeEvent(ByVal sender As Object, ByVal e As PaymentMadeEventArgs)
Public Event PaymentEvent As PaymentMadeEvent
Private _paymentAmount As Decimal
Public Property PaymentAmount As Decimal
Get
Return _paymentAmount
End Get
Set(ByVal value As Decimal)
_paymentAmount = value
AmountBox.Text = String.Format("{0:c}", _paymentAmount)
End Set
End Property
Private Sub PayButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PayButton.Click
Dim total As Decimal = 0
Try
total = Decimal.Parse(AmountBox.Text.TrimStart("₱")) - Decimal.Parse(PaymentBox.Text)
Catch
MessageBox.Show("Error Occured, please enter a valid amount!")
Return
End Try
If (total > 0) Then
AmountBox.Text = total.ToString()
Else
MessageBox.Show("Please give " + String.Format("{0:c}", -total))
RaiseEvent PaymentEvent(Me, New PaymentMadeEventArgs() With {.PaymentSuccess = True})
End If
End Sub
Public Class PaymentMadeEventArgs
Inherits EventArgs
Private _paymentSuccess As Boolean
Public Property PaymentSuccess As Boolean
Get
Return _paymentSuccess
End Get
Set(ByVal value As Boolean)
_paymentSuccess = value
End Set
End Property
End Class
End Class
ExecuteReader executes the command (the insert) but it has been built to return the rows extracted by a SELECT command.
Calling Read to discover if your INSERT has been successful is meaningless in this context.
You should call ExecuteNonQuery, catch the return value, and if it is not equal to zero, then you have inserted the record.
Private Sub paymentSuccessQuery(ByVal itemid, ByVal itemname)
Using mydbcon = New MySqlConnection("server=localhost;userid=root;password=;database=sdudb"
Try
mydbcon.Open()
Dim Query As String
Query = "INSERT INTO transaction (itemid, itemname) " & _
"VALUES(#id, #name)"
Using COMMAND = New MySqlCommand(Query, mydbcon)
COMMAND.Parameters.Add("#id", MySqlDbType.VarChar).Value = itemid
COMMAND.Parameters.Add("#name", MySqlDbType.VarChar).Value = itemname
Dim rowsAdded = COMMAND.ExecuteNonQuery()
if rowsAdded = 0 Then
MessageBox.Show("Unable to save transaction!")
Else
MessageBox.Show("Transaction Saved!")
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
Notice also the I have changed your code to use the appropriate Using statement around the disposable objects like the connection and the command and, of utmost importante, I have changed your query to use a more safe parameterized query approach (not sure about the MySqlDbType for the ID parameter, it seems to be an integer but in your original query you put it between single quotes like a string)

Save changes to DataGridView (filled using MySqlHelper) into MySql database

I'm trying to update a MySQL database on the basis of changes in the DataGridView.
I'm currently using this code to fill the DGV:
Private Sub Load_in_DGV_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Load_in_DGV.Click
Dim ds As DataSet '= New DataSet
Dim mTbl As DataTable
Dim sqlQRY$ = "SELECT `FirstName`, `LastName`, `Age` FROM `persons` WHERE `Age` > 25"
ds = MySqlHelper.ExecuteDataset(CnStr, sqlQRY)
mTbl = ds.Tables(0)
DataGridView1.DataSource = mTbl
End Sub
But all post and guides I read seem to use a DataAdapter and not to use MySqlHelper, so I'm asking if it's possible to save changes to database using my current code (and what's the way) and, otherwise, what are minimum changes to do in my code.
I know there is the command "mysqlhelper.UpdateDataSet" which has the following syntax:
Public Shared Sub UpdateDataSet (_
ConnectionString ByVal As String, _
CommandText ByVal As String, _
ByVal ds As DataSet, _
ByVal TableName As String _
)
but I have not found any example of use.
I did not understand what to send as "commandText".

updating fields in microsoft access 2000 thru visual basic

i created a program that add and returns equipment, my problem is, its because my borrowing table and my return equipments table are in one table only..representing these fields
"productnumber"
"productname"
"dateborrowed"
"datereturned"
"borrowername"
"status"
what i want to do here is when a user returns an equipment, entering the same data on the fields would make errors on my database..especially on my productnumber because that is my primary key, so i decided to have a data grid in my return equipment form, so if a user return an equipment, all i will do is to update the datereturned field in my database..guys? can you help me with the codes?
As you have not indicated what it you specifically you need help with, I'll start by giving you the simple query to perform the update then I am going on to show you how to interact with Access.
The query to update datereturned:
str = "UPDATE 'Your Table Name' SET datereturned = " & now ' This is your update query.
First thing to do is create a connection the the Access Database:
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0; Ole DB Services=-4; Data Source=D:\Tecnical Stu"& _
"dy\Complete_Code\Ch08\data\NorthWind.mdb"
Dim dbConnection As System.Data.IDbConnection = New System.Data.OleDb.OleDbConnection(connectionString )
Found at:
http://p2p.wrox.com/ado-net/28703-how-vbulletin-net-connect-access-database.html
Next you should perform the update:
dbConnection .Open()
str = "UPDATE 'Your Table Name' SET datereturned = " & now ' This is your update query.
'string stores the command and CInt is used to convert number to string
cmd = New OleDbCommand(str, cn)
icount = cmd.ExecuteNonQuery
Here is a class that will allow you to perform the interactions, easily and simply.
Imports System.Data.OleDb
Public Class Form1 Inherits System.Windows.Forms.Form
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e as _
System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
Try
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;_
Data Source=C:\emp.mdb;")
'provider to be used when working with access database
cn.Open()
cmd = New OleDbCommand("select * from table1", cn)
dr = cmd.ExecuteReader
While dr.Read()
TextBox1.Text = dr(0)
TextBox2.Text = dr(1)
TextBox3.Text = dr(2)
' loading data into TextBoxes by column index
End While
Catch
End Try
dr.Close()
cn.Close()
End Sub
End Class
When you run the code and click the Button, records from Table1 of the Emp database will be displayed in the TextBoxes.
Retrieving records with a Console Application
Imports System.Data.OleDb
Imports System.Console
Module Module1
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Sub Main()
Try
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\emp.mdb;_
Persist Security Info=False")
cn.Open()
cmd = New OleDbCommand("select * from table1", cn)
dr = cmd.ExecuteReader
While dr.Read()
WriteLine(dr(0))
WriteLine(dr(1))
WriteLine(dr(2))
'writing to console
End While
Catch
End Try
dr.Close()
cn.Close()
End Sub
End Module
Code for Inserting a Record
Imports System.Data.OleDb
Public Class Form2 Inherits System.Windows.Forms.Form
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Dim icount As Integer
Dim str As String
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button2.Click
Try
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\emp.mdb;")
cn.Open()
str = "insert into table1 values(" & CInt(TextBox1.Text) & ",'" & TextBox2.Text & "','" &_
TextBox3.Text & "')"
'string stores the command and CInt is used to convert number to string
cmd = New OleDbCommand(str, cn)
icount = cmd.ExecuteNonQuery
MessageBox.Show(icount)
'displays number of records inserted
Catch
End Try
cn.Close()
End Sub
End Class
Found at:
http://www.startvbdotnet.com/ado/msaccess.aspx
You need to split the product and borrow/return data into two tables:
product:
"productnumber"
"productname"
borrowed:
borrowedID (use a simple autonumber)
productnumber (foreign key linked to productnumber in the product table)
"dateborrowed"
"datereturned"
"status"
borrowerID (foreign key linked to borrower table)
a third table for borrowers/customers would also be in order
borrowers:
borrowerID
"borrowername"