.NET - Importing class with connection to database - mysql

I want to import a class to another class so that I don't have to write the same code X times.
I have a file with the connection to the database called connectDB.vb.
Imports MySql.Data.MySqlClient
Namespace connectDB1
Public Class connectDB
Dim connection As New MySqlConnection("Server=localhost; UserId=root;
Password=root; Database=something")
Public Sub doConnection()
Try
connection.Open()
Catch ex As Exception
MsgBox("Error")
End Try
End Sub
End Class
End Namespace
And I want to import connectDB.vb to File1.vb
Imports MySql.Data.MySqlClient
Imports MyApp.connectDB1
Public Class File1
Dim connectDataBase As New connectDB
Dim connection As New MySqlConnection("Server=localhost; UserId=root; Password=root; Database=something")
Private Sub File1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'doConnection()
connectDataBase.doConnexion()
End Sub
'Private Sub doConnection()
' Try
' connection.Open()
' Catch ex As Exception
' MsgBox("Error")
' End Try
'End Sub
Private Sub addProduct()
Dim dbcomm As MySqlCommand
Dim dbread As MySqlDataReader
If txtBoxQuantity.Text <> "" And txtBoxPrice.Text <> "" And txtBoxProduct.Text <> "" Then
dbcomm = New MySqlCommand("insert into products (price, stock, name) values(#price, #stock, #name)", connection)
dbcomm.Parameters.AddWithValue("#price", txtBoxPrice.Text())
dbcomm.Parameters.AddWithValue("#stock", txtBoxQuantity.Text())
dbcomm.Parameters.AddWithValue("#name", txtBoxProduct.Text())
dbread = dbcomm.ExecuteReader() ' GIVES ERROR
dbread.Close()
End If
End Sub
Private Sub add_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles agregarProducto.Click
addProduct()
End Sub
End Class
But when I run this code that it's suposed to save the data in the DB it gives me this error:
InvalidOperationException was unhandled. Connection must be valid and open.
connectDB.vb connects to the database since I debugged and it connects to the DB, but when I want to do some sql sentence in the File1.vb it gives that error.
Without trying to import the class the code works, but I'm just trying to improve my code, as you can see the commented code is the code I used to connect to the database.

Try adding this
Public Sub New()
connectDataBase = New connectDB()
connection = New MySqlConnection("Server=localhost; UserId=root; Password=root; Database=something")
End Sub

Related

How to perform a connection to a mdf database with mysql in vb

I wanted to make a connection to my Clients.mdf database with MySql but I'm not finding out where the error is.
Imports MySql.Data.MySqlClient
Imports Microsoft.Reporting.WinForms
Public Class Form8
Private Kon As New
I wanted to make a connection to my Clients.mdf database with MySql but I'm not finding out where the error is
MySqlConnection("Server=C:\Users\Utilizador\Desktop\
ClinicaProject\Clinica.mdf ;user id= ;database= Clinica.mdf")
Private Sub Form8_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub VoltarToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles VoltarToolStripMenuItem.Click
Me.Hide()
Form1.Show()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cmd As MySqlCommand
Dim adp As New MySqlDataAdapter
Dim sql As String
sql = "Select * From Consultas Where Data = '" & DateTimePicker1.Text & "'"
Try
Me.DataSet1.Clear()
Kon.Open()
cmd = New MySqlCommand(sql, Kon)
adp.SelectCommand = cmd
adp.Fill(Me.DataSet1.Consultas)
cmd.Dispose()
adp.Dispose()
Kon.Close()
Catch ex As Exception
Kon.Close()
MessageBox.Show(ex.Message)
End Try
Me.ReportViewer1.RefreshReport()
End Sub
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
End Sub
End Class

MySQL query (sum) not working in VB

I want to add the ages of all the employees in MySQL database column(using sum query) and then want to display its result(the value)on the click of a button in VB in a textbox.I have given a try but its not working.I am not able to figure this out.Please help....Image
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim Mysqlconn As New MySqlConnection
Mysqlconn.ConnectionString = "server=localhost;userid=root;port=85;password=andy1234;database=data"
Try
Mysqlconn.Open()
command.Connection = Mysqlconn
command.CommandText = "select sum(age) from data.etable"
Dim sqlresult As Object
sqlresult = command.ExecuteScalar
Dim str As String
str = sqlresult
TextBox5.Text = str
Mysqlconn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Mysqlconn.Dispose()
End Try
End Sub
a demo on standard port 3306 for Mysql
Schema
create table etable
( eid int auto_increment primary key,
age int not null
);
insert etable(age) values (1),(2),(3);
VB Code
Imports MySql.Data.MySqlClient
Public Class Form1
Dim conn As New MySqlConnection
Public Sub connect()
' Perform a connection test, and save ConnectionString
' in Module-level variable "conn"
Dim dbname As String = "dbname"
Dim hostname As String = "hostname"
Dim user As String = "dbuser"
Dim password As String = "password"
If Not conn Is Nothing Then conn.Close()
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}", hostname, user, password, dbname)
Try
conn.Open()
MsgBox("Connection Test Successful")
' and ConnectionString set for subsequent queries
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close() ' close connection for now
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
connect()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim iAgeSum As Integer
Try
conn.Open()
Catch ex As Exception
End Try
Dim cmd As New MySqlCommand(String.Format("select sum(age) as ageSum from etable"), conn)
Dim result = cmd.ExecuteScalar()
If result Is Nothing Then
TextBox1.Text = "junk"
Else
iAgeSum = Convert.ToInt32(result.ToString()) ' for the purpose of showing conversion
TextBox1.Text = iAgeSum
End If
conn.Close()
End Sub
End Class
Screenshot

Load excel to datagridview using vb.net as language and MySQL as Database

I watched a tutorial and all codes where copied except for the path. But i get the error Could not find installable ISAM in the cn.open()
Here is the overall code:
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cn As New OleDbConnection("Provider=Microsoft.Jet.OlEDB.4.0; Data Source:G:\Book1.xlsx;Extend Properties=Excel 8.0;")
cn.Open() <--Error Here
Dim da As New OleDbDataAdapter("Select * from [Sheet1$]", cn)
Dim dt As New DataTable
With DataGridView1
.AllowUserToAddRows = False
.DataSource = dt
End With
dt.Dispose()
dt = Nothing
da.Dispose()
da = Nothing
With cn
.Close()
.Dispose()
End With
cn = Nothing
End Sub
End Class
I hope anyone could help me. Thanks
Since you are using an .xlsx file, you need to use the ACE.OLDB.12.0 driver:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\Book1.xlsx;Extended Properties=Excel 12.0"
Notice the Source is assigned using and "=" sign, not a colon ":"

saving the path of the picture in MYSQL database using visual basic 2010

I try to save the "path" on MYSQL database but I get the error
the datatype of photo is BLOB
database is imageupload
table is student
hope someone can help me to fix my error and order to save the path on database
thanks a lot more power to us!!!
My error is that
"The connection cannot be used to perform this operation. It is either closed or invalid in this context."
My connection in module
Module Module1
Public cn As New ADODB.Connection
Public rs As New ADODB.Recordset
Sub konek()
With cn
.ConnectionString = "DRIVER={MY SQL ODBC 5.1 driver};SERVER=localhost;PWD=;UID=root;database=imageupload"
End With
End Sub
End Module
======================================================================
My form in Visual Basic 2010
Public Class Form1
Private Sub btnbrowsepic_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnbrowsepic.Click
OpenFileDialog1.FileName = ""
With OpenFileDialog1
.InitialDirectory = "C:\"
.Filter = "All Files|*.*|Bitmaps|*.bmp|GIFs|*.gif|JPEGs|*.jpg"
.FilterIndex = 2
End With
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
With PictureBox1
.Image = Image.FromFile(Me.OpenFileDialog1.FileName)
.SizeMode = PictureBoxSizeMode.StretchImage
End With
End If
Me.lblpath.Text = Me.OpenFileDialog1.FileName.ToString
End Sub
Private Sub btnsavepic_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsavepic.Click
rs = New ADODB.Recordset
rs.Open("select * from student", cn, 3, 3)----- error is here when i save the path on my database
With rs
.AddNew()
.Fields("photo").Value = "" & lblpath.Text
.Update()
MsgBox("Data has been saved")
End With
End Sub
End Class

Access to MySQL after closing connection

I have a problem with access to my datebase MySQL after closing it. I use Windows Form and MySql Connector from MySql official website to connect to datebase. I use MySQL in XAMPP.
If I open my connection I can do a simple query. But when I close a connection I can still do this query. Why?
Here is my code:
Imports MySql.Data.MySqlClient
Public Class Form1
Dim polaczenieMySql As New MySqlConnection
Dim mySQL As PolaczenieMySQL
Public Sub New()
InitializeComponent()
mySQL = New PolaczenieMySQL(Me)
End Sub
Private Sub btnPolaczMySQL_Click(sender As Object, e As EventArgs) Handles btnPolaczMySQL.Click
mySQL.Polacz()
End Sub
Private Sub RozlaczMySQL_Click(sender As Object, e As EventArgs) Handles btnRozlaczMySQL.Click
mySQL.Rozlacz()
End Sub
Private Sub btnZapytanie_Click(sender As Object, e As EventArgs) Handles btnZapytanieMySQL.Click
Dim zapytanie As String = "SELECT title, price, book_id from books"
mySQL.WykonajZapytanie(zapytanie)
End Sub
End Class
And my connection class:
Imports MySql.Data.MySqlClient
Public Class PolaczenieMySQL
Dim polaczenie As MySqlConnection = New MySqlConnection()
Dim glowneOkno As Form1
Public Sub New(form As Form1)
glowneOkno = form
End Sub
Public Sub Polacz()
polaczenie.ConnectionString = ("server=localhost;user id=root;password=;database=test")
Try
polaczenie.Open()
MessageBox.Show("Połączono z bazą danych MySQL.")
glowneOkno.labelPolaczenieMySQL.Text = "Połączono"
glowneOkno.labelPolaczenieMySQL.ForeColor = Color.Green
Catch myerror As MySqlException
MessageBox.Show("Nie udało się połączyć z bazą danych MySQL: " & myerror.Message)
End Try
End Sub
Public Sub Rozlacz()
Try
polaczenie.Close()
MessageBox.Show("Rozłączono z bazy danych MySQL.")
glowneOkno.labelPolaczenieMySQL.Text = "Nie połączono"
glowneOkno.labelPolaczenieMySQL.ForeColor = Color.Red
Catch myerror As MySqlException
MessageBox.Show("Błąd rozłączenia z bazy danych MySQL: " & myerror.Message)
Finally
polaczenie.Dispose()
End Try
End Sub
Public Sub WykonajZapytanie(ByVal zapytanie As String)
Dim SDA As New MySqlDataAdapter
Dim dbDataSet As New DataTable
Dim bSource As New BindingSource
Try
Dim komenda As MySqlCommand = New MySqlCommand(zapytanie, polaczenie)
SDA.SelectCommand = komenda
SDA.Fill(dbDataSet)
bSource.DataSource = dbDataSet
glowneOkno.DataGridViewMySQL.DataSource = bSource
SDA.Update(dbDataSet)
Catch ex As MySqlException
MessageBox.Show("Nie jesteś połączony z bazą")
End Try
End Sub
End Class
As I said before, after closing connection (mySQL.Rozlacz()) I can still do a query (mySQL.WykonajZapytanie(zapytanie)). What is wrong with this?
PS. Sorry for my polish names
If you look at the docs about the DbDataAdapter you could read this remark
The Fill method retrieves the data from the data source using a SELECT
statement. The IDbConnection object associated with the select command
must be valid, but it does not need to be open. If the IDbConnection
is closed before Fill is called, it is opened to retrieve data and
then closed. If the connection is open before Fill is called, it
remains open.
The MySqlDataAdapter inherits from the DbDataAdapter and there is no override of the Fill method, so it is the inherited class (DbDataAdapter) that works with the associated command, reopening the closed connection and then closing it.
EDIT
You asked also how to avoid this behavior, well you could add a boolean property to your class PolaczenieMySQL that maintains the state of your MySqlConnection
Private _isDead As Boolean
Public Property IsDead() As Boolean
Get
Return _isDead
End Get
Private Set(ByVal value As String)
_isDead = value
End Set
End Property
Now you could set this property to False when you open the connection and True when you close it.
Then check its value before executing the WykonajZapytanie sub
Public Sub WykonajZapytanie(ByVal zapytanie As String)
Dim SDA As New MySqlDataAdapter
Dim dbDataSet As New DataTable
Dim bSource As New BindingSource
if Me.IsDead Then
Throw new Exception("Invalid usage of this class")
End If
......
End Sub
Notice that there is a simpler check using the MySqlConnection property State
if polaczenie.State <> ConnectionState.Open Then
......
but, given the fact that in your Rozlacz method you dispose the connection I suggest to implement the first workaround.
Finally, I really think that you should change the whole pattern of usage. The connection should be opened, used and closed in the same method where it is required. Your actual infrastructure render this impossible. It is better to get rid of the Polacz and Rozlacz and use the mentioned pattern without the need of a global variable for the connection.