I am working on a application and I wrote the code below,
Public Function CreateDatatable(ByVal SqlQuery As String, ByVal strTable As String, Optional ByVal OrderbyField As String = "") As DataTable
If InitDB() Then
Try
Dim sqlAdapter As New MySqlDataAdapter()
Dim dt As New DataTable()
If SqlQuery = "" Then SqlQuery = "Select * from " & strTable & IIf(OrderbyField <> "", " order by " & OrderbyField, "")
Dim cmd As New MySqlCommand(SqlQuery, MySQLCon)
cmd.CommandTimeout = 18000
sqlAdapter.SelectCommand = cmd
dt.TableName = strTable
sqlAdapter.Fill(dt)
CreateDatatable = dt
Catch ex As Exception
ServiceLog.WriteEntry("CreateDatatable Exception:" & ex.Message)
End Try
Else
CreateDatatable = Nothing
End If
End Function
After running the code this error occurred.
MySql.Data.MySqlClient.MySqlException={"Fatal error encountered during
command execution."}
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
at AgilityNewsService.clsDataware_MySQL.CreateDatatable(String SqlQuery, String strTable, String OrderbyField) in C:\ISMSCleanDesktop\DesktopBkup_Tue10-22-2013\AgilityNewsService\AgilityNewsService\AgilityNewsService\clsDataware_MySQL.vb:line 48
How to resolve the above error?
Related
How to Connection all my forms using only one time setup database?
what's happening to me now is every form i made i always put my database connection
Create a module and make a shared function that you can call it from anywhere.
to get data to your dataset call it from anywhere within your project
Try
Dim dsEmployee As New DataSet()
dsEmployee = ExecuteDataSet("select * from tblEmployee")
Catch ex As Exception
MessageBox.Show("Getting error while getting dataset. " + ex.Message.ToString(), "Data Base", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
for insert records to your database
ExecuteNonQuery("insert into tblEmployee(Emp_ID,Emp_Code,Emp_Name,Emp_Mobile)values(1,'EMP1','Anand','+91 98000000')")
Create a module and make all required function and put your database connection string to MyConnection string vaiable
Option Explicit On
Imports System.Data.SqlClient
Module dbConnect
Dim MyConnection As String = "data source=MyPc;Initial Catalog=TestDb;User ID=sa;Password=12345;"
Public Function ExecuteDataSet(ByVal _Query As String) As DataSet
Dim dsReturn As New DataSet
Try
Dim conn As String = MyConnection
Using con = New SqlConnection(conn)
con.Open()
Dim cmd1 As New SqlCommand(_Query)
cmd1.Connection = con
Dim da As New SqlDataAdapter(cmd1)
dsReturn = New DataSet
da.Fill(dsReturn)
con.Close()
End Using
Catch ex As Exception
MessageBox.Show("Error While Getting DataSet :" + vbNewLine + ex.Message.ToString(), " ERROR ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Return dsReturn
End Function
Public Function ExecuteNonQuery(ByVal _Query As String) As Integer
Dim res As Integer = 0
Try
Dim conn As String = MyConnection
Using con = New SqlConnection(conn)
Dim cmd = New SqlCommand()
cmd.Connection = con
con.Open()
cmd.CommandText = _Query
cmd.Connection = con
res = cmd.ExecuteNonQuery
con.Close()
End Using
Catch ex As Exception
MessageBox.Show("Error While Inserting Records :" + vbNewLine + ex.Message.ToString(), " ERROR ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Return res
End Function
End Module
I have a textbox, button, and datagridview in my form. When i click the button, system will grab a table depending on my textbox from the database and show on datagridview.
I getting this error when i click the button. Where am I wrong?
here is my dbconn
Module mod_dbconn
Public conn As MySqlConnection
Public Sub openDB()
Dim dbname As String = scr_sales.btn_dbswitch.Text
Dim server As String = "localhost"
Dim user As String = "root"
Dim password As String = ""
Try
conn = New MySqlConnection
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", server, user, password, dbname)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
This is my form
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim query As String = "SELECT * FROM '" + TextBox1.Text + "'"
Dim cmd As New MySqlCommand(query, conn)
Dim da As New MySqlDataAdapter(cmd)
Dim dt = New DataTable
Dim cb As MySqlCommandBuilder
cb = New MySqlCommandBuilder(da)
DataGridView1.Refresh()
Try
conn.Open()
da.Fill(dt)
Dim bsource As New BindingSource
bsource.DataSource = dt
Me.DataGridView1.DataSource = bsource
da.Update(dt)
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
You are trying to build a dynamic table select so for the table name you don't need the quotes around the tablename
"SELECT * FROM " + TextBox1.Text + " ;"
This is my code for read data from EXCEL file using ODBC driver and write in MySql Database.
Public Class WebForm3
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim MySqlCmd = New SqlCommand()
' Dim dialog As New System.Windows.Forms.OpenFileDialog()
'Dim dialog As New OpenFileDialog()
'dialog.Filter = "Excel files |*.xls;*.xlsx"
'dialog.InitialDirectory = "C:\"
'dialog.Title = "Select file for import"
'If dialog.ShowDialog() = DialogResult.OK Then
Try
Dim dt As DataTable
Dim buff0 As String
Dim buff1 As String
Dim buff2 As String
dt = ImportExceltoDatatable("C:\\Book1.xls")
For i = 0 To dt.Rows.Count - 1
buff0 = dt.Rows(i)(0)
buff1 = dt.Rows(i)(1)
buff2 = dt.Rows(i)(2)
Dim connStr As String = "server=localhost;user=root;database=ajaxsamples;port=3306;password=innoera;"
Dim connMysql As MySqlConnection = New MySqlConnection(connStr)
Dim sql As String = "INSERT INTO ajaxsamples.customers VALUES('" & buff0 & "','" & buff1 & "','" & buff2 & "')"
Dim cmd As MySqlCommand = New MySqlCommand(sql, connMysql)
cmd.ExecuteNonQuery()
cmd.Dispose()
connMysql.Close()
Next
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Critical)
End Try
'End If
End Sub
Public Shared Function ImportExceltoDatatable(filepath As String) As DataTable
' string sqlquery= "Select * From [SheetName$] Where YourCondition";
Dim dt As New DataTable
Try
Dim ds As New DataSet()
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filepath & ";Extended Properties=""Excel 12.0;HDR=YES;"""
Dim con As New OleDbConnection(constring & "")
con.Open()
Dim myTableName = con.GetSchema("Tables").Rows(0)("TABLE_NAME")
Dim sqlquery As String = String.Format("SELECT * FROM [{0}]", myTableName)
'Dim myTableName = con.GetSchema("Tables").Rows(0)("TABLE_NAME")
'Dim sqlquery As String = String.Format("SELECT * FROM Sheet1$") ' "Select * From " & myTableName
Dim da As New OleDbDataAdapter(sqlquery, con)
da.Fill(ds)
dt = ds.Tables(0)
Return dt
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Critical)
Return dt
End Try
End Function
End Class
I got this error,
"Connection must be valid and open "
whats wrong in code? I am newbie for VB. Any help would be appreciated.
You forgot to open your connection.
Try
connMysql = New MySqlConnection
connMysql.ConnectionString = connStr
connMysql.Open() 'You forgot to open your connection
sql = "SELECT * FROM users"
cmd = New MySqlCommand(sql, connMysql)
cmd.ExecuteNonQuery()
cmd.Dispose()
Catch ex As Exception
'your error code here
Finally
connMysql.Close() 'close your connection
End Try
I'm working on simple project to figure out how databases work.
I created mysql base on my host and used this code to connect to it
Private mysql_host = "myhost"
Private mysql_user = "myuser"
Private mysql_pass = "mypw"
Private mysql_db = "mydb"
Private SQLConnect As String = "Server=" + mysql_host + ";" + "User Id=" + mysql_user + ";" + "Password=" + mysql_pass + ";" + "Database=" + mysql_db
Private SQLConnection As New MySqlConnection
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
sqlConnection.ConnectionString = SQLConnect
Try
If sqlConnection.State = ConnectionState.Closed Then
sqlConnection.Open()
MsgBox("Connected")
Else
sqlConnection.Close()
MsgBox("Not Connected")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
After that i used this code to add record into database.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim SQLStatement As String = "INSERT into tCodes(Code) VALUES ('" & TextBox1.Text & "')"
Dim cmd As New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
MsgBox("Added")
End Sub
On the other form i want to check if record exist in database. How to do that .
I tried with code
Dim SQLStatement As String = "SELECT * From tCodes WHERE Code '" & TextBox1.Text & "'")
For read . Me using this
Private host As String = "host" 'Host DB
Private user As String = "user" 'User DB
Private pass As String = "pass" 'Pass DB
Private base As String = "base" 'Base
Private conn As String = "Database=" & base & ";Data Source=" & host & ";User Id=" & _
user & ";Password=" & pass 'Connection
Private Connection As New MySqlConnection(conn) 'Connection
Private readData As MySqlDataReader 'Data Reader
Private adaptsData As New MySqlDataAdapter 'Data Adapter
Private command As New MySqlCommand 'command
Private ds As New DataSet 'DataSet
After
Public Function __select(Optinal table as String = "tCodes") As String
Try
Connection.Open()
Dim query As String = "SELECT * FROM " & table
command.CommandText = query
command.Connection = conexiune
adaptsData.SelectCommand = comanda
adaptsData.Fill(ds, tabla)
Dim newvalue As String = ds.Tables(tabla).Rows(0).Item(item)
ds.Dispose()
ds.Clear()
Connection.Close()
Return newvalue
Catch ex As Exception
ds.Dispose()
ds.Clear()
conexiune.Close()
msgbox(ex.message)
End Try
End Function
Dim conn As MySqlConnection
Dim sqlquery = "SELECT * FROM tCodes WHERE Code = '" + txtCode.Text + "'"
Dim myCommand As New MySqlCommand()
myCommand.Connection = conn
myCommand.CommandText = sqlquery
'start query
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader()
'see if user exists
If myData.HasRows = 0 Then
MsgBox("Kod je nevazeci")
conn.Close()
Else
MsgBox("Kod je vazeci")
End If
That was the solution of this problem
I'm trying to create a vb.net class to manage a MySQL database connection and i have a method Connect wich is suposed to assign the connection string to a mysqlconnection variable but i'm always getting the error:
An unhandled exception of type 'System.NullReferenceException'
occurred in Projecto_Aula.exe Additional information: Object reference
not set to an instance of an object.
DatabaseManager.vb
Imports MySql.Data.MySqlClient
Public Class DatabaseManager
Private connetionString As String = vbNullString
Private sqlReader As MySqlDataReader
Private sqlAdapter As MySqlDataAdapter
Private sqlCommand As MySqlCommand
Private sqlConnection As MySqlConnection
Sub New(ByVal host As String, ByVal user As String, ByVal password As String, Optional ByVal database As String = "requisicoes")
connetionString = "server=" & host & "; uid=" & user & "; pwd=" & password & "; database=" & database
MsgBox(connetionString)
End Sub
Public Sub Connect()
If (sqlConnection.State = ConnectionState.Open) Then ''throws exception when run
MsgBox("Already connected to the database.")
Return
End If
sqlConnection.ConnectionString = connetionString.ToString()
If (connetionString = vbNullString) Then
MsgBox("Invalid Connection String!")
Application.Exit()
End If
Try
sqlConnection.Open()
Catch ex As MySqlException
MsgBox("Error connecting: " & ex.ToString())
Application.Exit()
End Try
End Sub
End Class
MainMenu.vb
Public Class Login
Public databaseManager As New DatabaseManager("localhost", "root", "", "requisicoes")
Private Sub Form1_Load_1(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
databaseManager.Connect() 'throws exception when run
End Sub
End Class
All of these are NOT set (null/Nothing):
Private sqlReader As MySqlDataReader
Private sqlAdapter As MySqlDataAdapter
Private sqlCommand As MySqlCommand
Private sqlConnection As MySqlConnection
You need to create the objects BEFORE you using then:
Me.sqlReader = New MySqlDataReader
Me.sqlAdapter = New MySqlDataAdapter
Me.sqlCommand = New MySqlCommand
Me.sqlConnection = New MySqlConnection
So in the Connect() method create a new MySqlConnection and replace "myConnectionString" with a valid connection string.
Public Sub Connect()
Me.sqlConnection = New MySqlConnection("myConnectionString")
Try
Me.sqlConnection.Open()
MsgBox(Me.sqlConnection.State.ToString())
Catch ex As MySqlException
MsgBox("Error connecting: " & ex.ToString())
Application.Exit()
End Try
End Sub
Change ur following line of code with this mention code
sqlConnection.ConnectionString = connetionString.ToString()
Change to:
sqlConnection.ConnectionString = Convert.ToString(connetionString)