mysql select statement not filling datatable - mysql

I have a MySQL object I am trying to select all data from and insert into a datatable however every time it gets to my first if statement regarding said datatable It gets a possible null value error
dbfile dbserver dbuser and dbpassw all are public variables set on on a module.
variable dimensions
Dim cnn As New MySqlConnection()
Dim cmd As New MySqlCommand
Dim adptr As New MySqlDataAdapter
Dim filltab As DataTable
code
Dim cb As New MySqlConnectionStringBuilder
cb.Database = dbfile
cb.Server = dbserver
cb.UserID = dbuser
cb.Password = dbpassw
Using cnn As New MySqlConnection(cb.ConnectionString)
Using cmd As New MySqlCommand("SELECT * from gpstracking", cnn)
Try
cnn.Open()
adptr = New MySqlDataAdapter(cmd)
adptr.Fill(filltab)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
If filltab.Rows.Count > 0 Then 'this is the row that the error for filltab being a null value hits
pop = 0
For pop As Integer = 0 To filltab.Rows.Count - 1
' WebBrowser1.Document.InvokeScript("AddMarker", New Object() {"Unit: " & filltab.Rows(pop)("unitnumb") & " at " & filltab.Rows(pop)("time"), filltab.Rows(pop)("lat"), table.Rows(pop)("long")})
Next
End If
End Using
End Using
one error on
adptr.Fill(filltab) 'Exception:Thrown: "Value cannot be null." (System.ArgumentNullException)
I also just noticed it is announcing "failure to collect details" on
Catch ex As Exception
MsgBox(ex.ToString)
End Try

I don't know vb syntax, but you have Dim filltab As DataTable without New (like in other dimensions), and I guess MySqlDataAdapter.Fill requires the argument to be not null. Just a guess.

instead of using this code
adptr = New MySqlDataAdapter(cmd)
adptr.Fill(filltab)
try use
filltab.load(cmd.ExecuteReader())

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..

vb 2010 mysql insert record operation inserts a blank record but no data is inserted

I am trying to develop a utility in vb 2010, which will store values from Datagridview control to a mysql table
Steps
1) Datagrid cell values are stored in an array
2) Array values are used .AddWithValue() function
Present status: Only a blank record is inserted. Data is missing.
Please refer to following code.
Function insertRec()
'dgExistingProject is datagridview control embedded on the form
Dim ServerString As String = "Server=pnserver;User ID=root;
Password=; Database=prayer_net"
Dim Arr(RCount) As String
Dim SQLConn As MySqlConnection = New MySqlConnection
SQLConn.ConnectionString = ServerString
dim I as Integer
For I = 0 To RCount
Arr(I) = dgExistingProject.Rows(I).Cells(1).Value
Next
Try
Dim dt As Date = DateTime.Now.ToString("yyyy/MM/dd
HH:mm:ss")
Dim projName as Integer=Arr(4)
Using sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = "INSERT INTO dyn_dwg_register
(file_name,file_location,dwg_description,
project_id,created_by, created_on)" & _
" values (#file_name, #file_location, #dwg_description, #project_id, #created_by, #created_on)"
.CommandType = CommandType.Text
.Connection = SQLConn
.Parameters.AddWithValue("#file_name", Arr(0))
.Parameters.AddWithValue("#file_location", Arr(1))
.Parameters.AddWithValue("#dwg_description", Arr(2))
.Parameters.AddWithValue("#project_id", ProjName)
.Parameters.AddWithValue("#created_by", Arr(4))
.Parameters.AddWithValue("#created_on", dt)
End With
Try
SQLConn.Open()
If SQLConn.State = ConnectionState.Open Then
Dim ID As Integer = sqlCommand.ExecuteNonQuery()
End If
Catch ex As Exception
MsgBox(ex.Message.ToString)
Finally
SQLConn.Close()
End Try
End Using
Catch e As Exception
MsgBox (e.Message.ToString)
End Try
End Function
Rajendra Nadkar
i had written a code in C# where i had to store data from a datagrid to SQL database. I used the following code. I think it will help you.
string sqlquery = "UPDATE TableName set ColumnName1=#param1 where ColumnName2=#param2";
using (OleDbCommand Cmd = new OleDbCommand(sqlQuery, dbCon))
{
Cmd.Parameters.AddWithValue("#param1", Convert.ToDouble(dataGridView1[1, index].Value));
Cmd.Parameters.Add(new OleDbParameter("#param2", OleDbType.VarWChar)).Value = "somevalue";
updateDbCmd.ExecuteNonQuery();
updateDbCmd.Parameters.Clear();
}
Funny, I changed the field name prefix # to ? and things became smooth. In an earlier question in Feb 11, Stelian Matei suggested this edit, though later on Giezel Esteves reversed it. (Original question asked by user1176607 in Feb '10)
I guess I need to refer to documentation more thoroughly. Anyways I am giving the working code here if you or anybody interested in it.
Dim qry As String = "INSERT INTO dyn_dwg_register (`file_name` , `file_location`, `dwg_description`, `project_id`, `created_by`)" & _
" values (?file_name, ?file_location, ?dwg_description, ?project_id, ?created_by)"
Dim sqlCommand As MySqlCommand
sqlCommand = New MySqlCommand(qry, SQLConn)
sqlCommand.CommandType = CommandType.Text
With sqlCommand
.Parameters.AddWithValue("?file_name", Arr(0))
.Parameters.AddWithValue("?file_location", Arr(1))
.Parameters.AddWithValue("?dwg_description", Arr(2))
.Parameters.AddWithValue("?project_id", ProjName)
.Parameters.AddWithValue("?created_by", Arr(2))
End With

Update mysql data or record using VB.net with datagridview

Hi guys I need help in updating the data on my datagridview. The Scenario is when I click the Search it will query the appropriate data and display that I want to the datagridview. Then I want to update if their any changes or deleted data from datagridview then also update to my mysql table for new data or record whenever I click the Update Button and it will prompts a messagebox if their is a successfully changes to my data and prompts if their is no changes to my data. I really need help the codes for update button.
Here is my code to the search button to the datagridview:
Imports MySql.Data.MySqlClient
Public Class Form1
Dim conn As New MySqlConnection
Dim result As Integer
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim ds As New DataSet
Dim dr As MySqlDataReader
Dim sql As String
Dim dt As New DataTable
Private Sub cmdSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSearch.Click
con.ConnectionString = ("server=127.0.0.1;user id=root;password=12345;database=dbsis3bkenth;")
Try
conn.Open()
sql = "SELECT LName,FName,MI FROM tblsisterbrother where IDNoBrodSis = '" & cbIDNo.Text & "'"
cmd = New MySqlCommand(sql, conn)
dr = cmd.ExecuteReader
dr.Read()
If dr.HasRows = True Then
MessageBox.Show("Record Found.!")
Else
MessageBox.Show("Record Unfound.!")
End If
dr.Close()
Catch ex As MySqlException
MessageBox.Show("Error in searching to database:error is:" & ex.Message)
Exit Sub
End Try
dr.Close()
RemoveHandler DataGridView1.CellValidating, AddressOf DataGridView1_CellValidating
Dim DataAdapter1 As MySqlDataAdapter = New MySqlDataAdapter
DataAdapter1.SelectCommand = cmd
DataAdapter1.Fill(ds, "tblsisterbrother")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "tblsisterbrother"
conn.Dispose()
conn.Close()
End Sub
Then I want a code for the update, it will be place here:
Private Sub cmdUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdUpdate.Click
I want this kind of messagebox appears if the rows affected, this code does not run to what I want, just for reference on how to update. Please help me :)
If DataGridView1.DataSource.GetChanges() Is Nothing Then
MessageBox.Show("The table contains no changes to save.")
Else
Dim rowsAffected As Integer = da.Update(dt)
If rowsAffected = 0 Then
MessageBox.Show("No rows were affected by the save operation.")
Else
MessageBox.Show(rowsAffected & " rows were affected by the save operation.")
End If
End If
End Sub
The problem lies in the fact that you use a different DataAdapter when you fill the grid from the one that you want to use when you update the database.
You could simply change the code that fills the grid and make use of the global dataadapter declared in the class
' Dim DataAdapter1 As MySqlDataAdapter = New MySqlDataAdapter'
da.SelectCommand = cmd
da.Fill(ds, "tblsisterbrother")
dataGridView1.DataSource = ds.Tables(0)
.....
Now when you call the Update method you are using the same adapter, just give it a littel help in building the required update/insert and delete command using a MySqlCommandBuilder
DataGridView1.EndEdit()
Dim dt As DataTable
dt = TryCast(DataGridView1.DataSource, DataTable)
If dt.GetChanges() Is Nothing Then
MessageBox.Show("The table contains no changes to save.")
Else
Dim builder = new MySqlCommandBuilder(da)
Dim rowsAffected As Integer = da.Update(dt)
If rowsAffected = 0 Then
MessageBox.Show("No rows were affected by the save operation.")
Else
MessageBox.Show(rowsAffected & " rows were affected by the save operation.")
End If
End If

Error when getting MySQL data in .NET

I'm creating a .NET web application that retrieves data from a database. I keep getting the following error when running the below code though.
Fatal error encountered during command execution.
The InnerException is {"Parameter '?Username' must be defined."}, but I can see that ?Username is defined and I know that Session("Username") is correct and exists.
Here is the code. It fails on the SupervisorNameAdapter.Fill(SupervisorNameData, "Data") line.
Dim SupervisorID As String = Session("Username")
Dim qryGetSupervisorName As String = "select * from USERS where UserID = ?Username"
Using cn As New MySqlConnection(ConfigurationManager.ConnectionStrings("ConnectionInfo").ConnectionString), cmd As New MySqlCommand(qryGetSupervisorName, cn)
cmd.Parameters.AddWithValue("?Username", SupervisorID)
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
Dim SupervisorNameAdapter As New MySqlDataAdapter(qryGetSupervisorName, cn)
Dim SupervisorNameData As New DataSet
SupervisorNameAdapter.Fill(SupervisorNameData, "Data")
If SupervisorNameData.Tables(0).Rows.Count = 0 Then
MsgBox("An error has occured. Please refresh the page.", vbOKOnly, "Error!")
Else
SupervisorName.Text = SupervisorNameData.Tables(0).Rows(0).Item(1) & " " & SupervisorNameData.Tables(0).Rows(0).Item(2)
End If
End Using
Does anyone know why this is happening?
You are not setting correctly the command to be used by the MySqlAdapter. You just pass the command text string and with that string the adapter build another command that is missing the required parameter
Just change your code to
Dim SupervisorID As String = Session("Username")
Dim qryGetSupervisorName As String = "select * from USERS where UserID = ?Username"
Using cn As New MySqlConnection(ConfigurationManager.ConnectionStrings("ConnectionInfo").ConnectionString), cmd As New MySqlCommand(qryGetSupervisorName, cn)
cmd.Parameters.AddWithValue("?Username", SupervisorID)
Dim SupervisorNameAdapter As New MySqlDataAdapter(cmd)
Dim SupervisorNameData As New DataSet
....
End Using

Loop through Database table and get all values of each record in turn

I need to get all the values of each record in a table, this is so I can then add them to a text file log, a record per line, and then delete them from the database. I'm new to this and have searched how to add SQL query results to an array or a generic list, but I don't fully understand them.
All I have so far is:
Private Sub btnClearAll_Click(sender As Object, e As EventArgs) Handles btnClearAll.Click
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Application Programming\Project\Issue Logger\Database\IssueLoggerDB.accdb"
Dim strSQl = "TRUNCATE TABLE CurrentJobs"
Dim commandInsert As New OleDbCommand
commandInsert.CommandText = strSQl
commandInsert.Connection = conn
commandInsert.Connection.Open()
commandInsert.ExecuteNonQuery()
Me.ReportViewer1.RefreshReport()
End Sub
This is for a Uni project, and above is how we have been to shown to do it, however nothing I have found while researching looks similar.
Feel free to use this procedure:
Private Sub DataTableToTextFile()
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Application Programming\Project\Issue Logger\Database\IssueLoggerDB.accdb"
Using conn As OleDbConnection = New OleDbConnection(connString)
Dim dt As New DataTable
conn.Open()
'Change the query. It's not a good practice to use '*' in your select queries. Please, use the column names instead.
Dim dataAdapter As New OleDbDataAdapter("SELECT * FROM CurrentJobs", conn)
dataAdapter.Fill(dt)
'Change the path to your desired path
Dim exportPath As String = "C:\Logs\"
Dim exportFileName As String = "log.txt"
'If directory does not exists, create it
If Not Directory.Exists(exportPath) Then
Directory.CreateDirectory(exportPath)
End If
'Write data into the text file
Dim writer As New StreamWriter(exportPath + exportFileName)
Try
Dim sb As New StringBuilder
For Each row As DataRow In dt.Rows
sb = New StringBuilder
For Each col As DataColumn In dt.Columns
sb.Append(row(col.ColumnName))
Next
writer.WriteLine(sb.ToString())
Next
Catch ex As Exception
Throw ex
Finally
If Not writer Is Nothing Then writer.Close()
End Try
'Finally clean database table
Dim strSQl = "Delete From CurrentJobs"
Dim commandDelete As New OleDbCommand(strSQl, conn)
'execute
commandDelete.ExecuteNonQuery()
'close connection
conn.Close()
End Using
End Sub