Code behide VB.connection string? - mysql

I am currently developing a webpage using ASP.NET with VB as back end. But I am facing a problem. I don't know how to make a database connection to connect with MYSQL WORKBENCH. I just wrote the connection but it just code for SQL server.
This is my sample code for connection but it for sql server. I just want code for mySQL workbench.
Imports System.Data
Imports System.Data.SqlClient
Partial Class Request
Inherits System.Web.UI.Page
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
txt1.Focus()
txt2.Focus()
txt3.Focus()
txt4.Focus()
txt5.Focus()
txt6.Focus()
txt7.Focus()
ddl1.Focus()
ddl2.Focus()
ddl3.Focus()
ddl4.Focus()
End Sub
Protected Sub btnsubmit_Click(sender As Object, e As EventArgs) Handles btnsubmit.Click
con.ConnectionString = "Server=localhost;Database=test;Uid=root;Pwd=1234;"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO cr_record (Emplid, Nama, date, DeptDesc, email, Change, reasonchange,problem,priority,reasondescription,systemrequest) VALUES (#Emplid, #Nama, #date, #DeptDesc, #email, #Change, #reasonchange,#problem,#priority,#reasondescription,#systemrequest)"
cmd.Parameters.AddWithValue("#Emplid", ddl1.Text)
cmd.Parameters.AddWithValue("#Nama", TextBox1.Text)
cmd.Parameters.AddWithValue("#date", txt5.Text)
cmd.Parameters.AddWithValue("#DeptDesc", txt2.Text)
cmd.Parameters.AddWithValue("#email", txt4.Text)
cmd.Parameters.AddWithValue("#Change", ddl2.Text)
cmd.Parameters.AddWithValue("#reasonchange", txt6.Text)
cmd.Parameters.AddWithValue("#problem", ddl3.Text)
cmd.Parameters.AddWithValue("#priority", rbl1.Text)
cmd.Parameters.AddWithValue("#reasondescription", txt7.Text)
cmd.Parameters.AddWithValue("#systemrequest", ddl4.Text)
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Added Successfully")
End Sub
End Class

You will need to download and reference the MySQL .NET Connector http://dev.mysql.com/downloads/connector/net/. You will then use the System.Data.MySqlClient namespace and replace your SqlConnection and SqlCommand with MySqlConnection and MySqlCommand

Related

How to connect datagrid and mysql database through adodb

I have to display a table in data grid in vb.net(visual studio 2008) using adodb from mysql.
but the following code not working .(No error are shown)
please help
I opted adodb due to error,even after many attempts ,using mysqldataadpter
Imports MySql.Data.MySqlClient
'Imports MySql.Data.Types
'Imports MySql.Data.VisualStudio
'Imports MySql.Data
Imports System.IO
Imports System.Data
Imports CrystalDecisions.CrystalReports.Engine
Public Class Form3
Dim sSQLQry As String
Dim ReturnArray
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim mrs2 As New ADODB.Recordset
Dim DBPath As String, sconnect As String
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
sconnect = "DRIVER={MySQL ODBC 8.0 Unicode Driver};Server=localhost;Database=stockauto;User=root;Password=;"
If Conn.State = 1 Then
Conn.Close()
End If
Conn.Open(sconnect)
sql2 = "SELECT * From STOCK"
mrs.Open(sql2, Conn)
If mrs.State = 1 Then
mrs.Close()
End If
mrs.Open(sql2, Conn)
DataGridView1.DataSource = mrs
DataGridView1.Refresh()
End Sub
First the connection string. See https://www.connectionstrings.com/mysql-connector-net-mysqlconnection/
I used the simplest example. Replace yourUserID and yourPassword with the real values.
Get rid of all the ADODB and ODBC stuff. This code uses ADO.net
Using...End Using blocks ensure that database objects are closed and disposed.
Private MySqlConnStr As String = "Server=localhost;Database=stockauto;Uid=yourUserId;Pwd=yourPassword;"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = GetStockData()
DataGridView1.DataSource = dt
End Sub
Private Function GetStockData() As DataTable
Dim dt As New DataTable
Using cn As New MySqlConnection(MySqlConnStr),
cmd As New MySqlCommand("SELECT * From STOCK", cn)
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
ADODB is the old mechanism from pre-.Net VB. It exists only for backwards compatibility with old code and should not be used for new development.
Try this, which uses the updated ADO.Net:
' Don't use the root account to connect to the database!
Private sconnect As String = "DRIVER={MySQL ODBC 8.0 Unicode Driver};Server=localhost;Database=stockauto;User=root;Password=;"
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim data As New DataTable
Using cn As New MySqlConnection(sconnect), _
cmd As New MySqlCommand("SELECT * FROM Stock", cn), _
da As New MySqlDataAdapter(cmd)
da.Fill(data)
End Using
DataGridView1.DataSource = data
DataGridView1.Refresh()
End Sub

Is there away to display the databases of a MySQL server, put it in a combobox, and display it's contents in a datagridview table in VB.Net?

I have a project for school wherein I need to do the above problem, however, our Prog teacher didn't properly fully teach us about mysql and binding it to VB.Net. So I am at a complete loss right now.
I am using Visual Basic.Net on Studio 2019.
Actually this is quite easy in MySql. Normally a connection string would include a database= clause but is this case you want a list of all databases.
My string looks like
Private ConStr As String = "server=localhost;user id=xxx;password=xxx"
Of course you would reference your server. The user id and password would probably need an account with admin privileges.
Private Sub DisplayDatabases()
Dim dt As New DataTable
Using cn As New MySqlConnection(ConStr),
cmd As New MySqlCommand("show databases", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
ComboBox1.DisplayMember = "Database"
ComboBox1.DataSource = dt
End Sub
Private Sub DisplayTables(DB As String)
Dim dt As New DataTable
Using cn As New MySqlConnection(ConStr),
cmd As New MySqlCommand($"use {DB}; show tables", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
DataGridView1.DataSource = dt
End Sub
Usage:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
DisplayDatabases()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
DisplayTables(ComboBox1.Text)
End Sub
I certainly wouldn't want to be displaying this much info to just any user.
if you are sure about that the server is mySQL you can add the MySql.Data.dll to your project first (MySQL Connector/NET), here is some code to guide you in your project:
Imports MySql.Data.MySqlClient
Public Class Form2
Private Sub Test()
Dim myConnection As MySqlConnection = New MySqlConnection("server=localhost; user id=root; password=yourpassword; database=yourDB; pooling=false;")
Dim strSQL As String = "SELECT * FROM my_users;"
Dim myDataAdapter As MySqlDataAdapter = New MySqlDataAdapter(strSQL, myConnection)
Dim myDataSet As DataSet = New DataSet()
myDataAdapter.Fill(myDataSet, "my_users")
MySQLDataGrid.DataSource = myDataSet
MySQLDataGrid.DataBind()
End Sub
End Class

Connect to mySQL with VB.NET from values

Im trying to connect to mySql, but I have problem locating where im doing wrong.
My form contain e a label that is a number thats going to be posted to Score and a textbox where the user typed their name to be posted in Navn.
My code so far is:
Imports System
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim connect As New SqlConnection("Data Source = mysqlAdress;Network Library= DBMSSOCN;Initial Catalog=**;User ID=**;Password=**;")
Dim query As String = "INSERT INTO 2048 VALUES(#score, #name)"
Dim command As New SqlCommand(query, connect)
command.Parameters.Add("#score", SqlDbType.Int).Value = Label1.Text
command.Parameters.Add("#navn", SqlDbType.VarChar).Value = TextBox1.Text
connect.Open()
connect.Close()
End Sub
Your table name should be enclosed in backticks like this:
Dim query As String = "INSERT INTO `2048` VALUES(#score, #name)"
Also try to avoid table names with such naming conventions ie., only numbers.
Also you are opening and closing the connection simultaneously.
connect.Open()
connect.Close()
Try like this:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim connectionString As String = "Data Source = mysqlAdress;Network Library= DBMSSOCN;Initial Catalog=**;User ID=**;Password=**;"
Using SQLConnection As New MySqlConnection(connectionString)
Using sqlCommand As New MySqlCommand()
With sqlCommand
.CommandText = "INSERT INTO `2048` VALUES(#score, #name)"
.Connection = SQLConnection
.CommandType = CommandType.Text
.Parameters.AddWithValue("#score", Label1.Text)
.Parameters.AddWithValue("#name", TextBox1.Text)
End With
Try
SQLConnection.Open()
sqlCommand.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox ex.Message.ToString
Finally
SQLConnection.Close()
End Try
End Using
End Using
End Sub

key word not supported 'data source'

im having problem in my connection. the error said that key word not supported in the data source and i dont what to do next. thanks in advance!
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class frmMasancayClinicSignupvb
Dim connection As New MySqlConnection
Dim myReader As MySqlDataReader
Dim Adapter As MySqlDataAdapter
Dim myCommand As MySqlCommand
Dim Dset As New DataSet
Dim table As New DataTable
Dim MyQuery As String
Dim i As Integer
Private Sub frmMasancayClinicSignupvb_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connection = New MySqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mark\Documents\MASANCAYCLINICLOGIN.mdf;Integrated Security=True;Connect Timeout=30")
Try
If connection.State = ConnectionState.Closed Then
connection.Open()
MsgBox("connected to database")
Else
connection.Close()
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
connection.Close()
End Sub
End Class
It appears that you're passing in the arguments for a SqlConnectionStringBuilder - that's for Microsoft's SqlServer database, not MySql. (see
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.integratedsecurity(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2 ).
MySqlConnection takes "Data Source" but doesn't take those other parameters. See :
http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlconnection.html#connector-net-examples-mysqlconnection-defctor

How to save data entry to MySQL database

I have an assignment where I have to develop a Windows application using Visual Basic .NET. From the form that I have designed, it should save all records in a table in a MySQL database. How should I do this? Here's what I've got so far:
Imports System.Data
Imports System.Data.SqlClient
Public Class AddMember
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
con.ConnectionString = "Data Source=|DataDirectory|\127.0.0.1"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO memberdetails (ID, Name, Surname, Age, Gender, Contact, Address) VALUES (#ID, #Name, #Surname, #Age, #Gender, #Contact, #Address)"
cmd.Parameters.AddWithValue("#ID", TextBox1.Text)
cmd.Parameters.AddWithValue("#Name", TextBox2.Text)
cmd.Parameters.AddWithValue("#Surname", TextBox3.Text)
cmd.Parameters.AddWithValue("#Age", TextBox4.Text)
cmd.Parameters.AddWithValue("#Gender", ComboBox1.Text)
cmd.Parameters.AddWithValue("#Contact", TextBox6.Text)
cmd.Parameters.AddWithValue("#Address", TextBox7.Text)
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Added Successfully")
End Sub
End Class
con.Open()-error 26
I think it has to do with your connection string. try this connection string format:
con.ConnectionString = "Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;"
and since your database server is MySQL, you shouldn't use System.Data.SqlClient namespace but instead use MySql.Data.MySqlClient namespace.