There is no row at position 0 Vb.net and Mysql - mysql

I'm trying to get and print data from a row "status" on the table "printer" and it keeps saying "There is no row at position 0."
Dim conn As New deepconnection()
Dim adapter As New MySqlDataAdapter()
Dim table As New DataTable()
Dim ds, ds1 As New DataSet
Dim command As New MySqlCommand("SELECT * FROM printer", conn.getConnection)
conn.openOcean()
PrinterStatus.Text = table.Rows(0).Item("status")
The connection:
Private fishcatch As New MySqlConnection("datasource=localhost;port=3306;username=root;password=xxxxx;database=deep_ocean")
' Get the connection only to read
ReadOnly Property getConnection() As MySqlConnection
Get
Return fishcatch
End Get
End Property
Open connection:
Sub openOcean()
If fishcatch.State = ConnectionState.Closed Then
fishcatch.Open()
End If
End Sub
What is wrong?

You haven't executed the command to fill the table. Without that part the table is still empty
Dim command As New MySqlCommand("SELECT * FROM printer", conn.getConnection)
conn.openOcean()
' Execute the command and pass the reader to the table load method
table.Load(command.ExecuteReader())
PrinterStatus.Text = table.Rows(0).Item("status")
Even after this the table could still be empty if there is no record in the database table named Printer, so before reading anything from a datatable check always the rows count
If table.Rows.Count > 0 Then
PrinterStatus.Text = table.Rows(0).Item("status")
...
End If

Related

how to update empty datatable by the data from another datatable

I have 2 servers that contain the same databases with the same structure (Main Server + Sub Server).
I deleted all data from the table in the sub server.
I got the data from the table from the main server and put it in Datatable.
I copied the data from the Datatable of the server2.
I use Dataadapter2 to update the table in the sub server.
but still, the sub server is empty?!
'Delete Data From The Sub Server
xSlConn.Open()
Dim xcmddelete As New MySqlCommand("Delete FROM tblplaces", xSlConn)
xcmddelete.ExecuteNonQuery()
'Get Data Drom The Main Server
Conn.Open()
Dim xcmd1 As New MySqlCommand("SELECT * FROM tblplaces", Conn)
Dim xdt1 As New DataTable
Dim xda1 As New MySqlDataAdapter(xcmd1)
xda1.Fill(xdt1)
'Preparing the datatable for the Sub Server
Dim xcmd As New MySqlCommand("SELECT * FROM tblplaces", xSlConn)
Dim xdt2 As New DataTable
Dim xda2 As New MySqlCommand(xcmd)
Dim xB As New MySqlCommandBuilder(xda2)
xda2.Fill(xdt2)
'Copt the data from the main datatable to the sub datatable
xdt2 = xdt1.Copy()
'Update The Datatable2
xB.GetUpdateCommand()
xda2.Update(xdt2)
xda2.Fill(xdt2)
This line of code is useless; the next line of code tosses out xdt2 anyway
xdt2 = xdt1.Copy()
This line duplicates the datatable. It won't set all the rows in xdt2 to be RowState of Added, which is what the datadapter needs them to be in order to run an insert on them
A dataadapter inspects each row's RowState. Unchanged rows are ignored. Added have the INSERT command run on them, Modified maps to UPDATE, Deleted maps to the DELETE query
Right now all the rows in your xdt1 are Unchanged because the dataadapter called AcceptChanges on them after it added them to the table
Now.. you don't need to copy the data at all; you can just set all the rows in xdt1 to be Added so the xdt2 adapter will use its INSERT command on them. Also, it should be possible to just swap the connection out on the insertcommand
'Get Data Drom The Main Server
Dim dt As New DataTable
Dim da As New MySqlDataAdapter("SELECT * FROM tblplaces", Conn)
da.Fill(dt)
Dim xB As New MySqlCommandBuilder(da)
da.InsertCommand.Connection = xSlConn
For Each ro as DataRow in xdt1.Rows
ro.SetAdded()
Next ro
da.Update(dt)
Or, you can simply request that the xda1 adapter NOT call AcceptChanges on them at all, so they will be in Added state already:
'Get Data Drom The Main Server
Dim dt As New DataTable
Dim da As New MySqlDataAdapter("SELECT * FROM tblplaces", Conn)
da.AcceptChangesDuringFill = False
da.Fill(dt)
Dim xB As New MySqlCommandBuilder(da)
da.InsertCommand.Connection = xSlConn
da.Update(dt)
Or if you're pushing to a different db
'Get Data Drom The Main Server
Dim dt As New DataTable
Dim da As New MySqlDataAdapter("SELECT * FROM tblplaces", Conn)
da.AcceptChangesDuringFill = False
da.Fill(dt)
Dim da2 as New SqliteDataAdapter("SELECT * FROM tblplaces", "put a connection string here")
Dim xB As New SqliteCommandBuilder(da2)
da2.Update(dt)
Note; this latter example uses eg SQLite as a demo of declaring two different adapters of different types for different db - it doesn't guarantee that eg the specific SQLite library you're using actually contains a dataadapter implementation (some don't)
First, you need to use Using...End Using blocks to make sure you database objects are disposed. Don't declare database connections and commands outside of the method where they are used.
Your main problem is the Fill method of the DataAdapter sets all rows to unchanged. I changed this to the DataTable.Load method which takes a parameter of LoadOption. This will preserve the RowState Added. Then when you call Update on the DataAdapter the row will be recognized. If the row is Unchanged the DataAdapter will not update the database.
Private ConStrMain As String = "Your Main server connection string"
Private ConStrSub As String = "Your Sub server connection string"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Delete Data From The Sub Server
Using conSub As New MySqlConnection(ConStrSub),
cmd As New MySqlCommand("Delete FROM tblplaces", conSub)
conSub.Open()
cmd.ExecuteNonQuery()
End Using
'Retrieve data from Main server
Dim dt As New DataTable
Using conMain As New MySqlConnection(ConStrMain),
cmd As New MySqlCommand("SELECT * FROM tblplaces", conMain)
conMain.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader, LoadOption.Upsert)
End Using
End Using
'Insert data from Main to Sub server
Using conSub As New MySqlConnection(ConStrSub),
da As New MySqlDataAdapter("SELECT * FROM tblplaces", conSub)
Dim sb As New MySqlCommandBuilder(da)
da.Update(dt)
End Using
End Sub

How to read a value from mysql database?

I want to be able to read a value (in this case an Group ID). All the topics and tutorials I've watched/read take the data and put it into a textbox.
I don't want to put it in a textbox in this case; I want to grab the Group ID and then say:
If Group ID = 4 then login
Here is an image of the database.
Basically, but none of the tutorials I watch or the multiple forums. None of them take a a value and say if value = 4 then login or do something else.
If text = "1" Then
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString =
"server='ip of server'.; username=; password=; database="
Dim READER As MySqlDataReader
Dim member_group_id As String
Try
MysqlConn.Open()
Dim Query As String
Query = "SELECT * FROM `core_members` where name='" & TextBox2.Text & "'"
Query = "SELECT * FROM `nexus_licensekeys` where lkey_key='" & TextBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
Here is what I have so far. I'm kind of new implementing mysql data with visual basic and only recently started to get into it. I'm not sure what comes next or how to even start with reading the group id etc.
As I said any help from here on out would be highly appreciated of how to read the group id and say if this group id = this number then do this or that. I'm sure you get the idea.
I divided the code into UI Sub, and Data Access Function that can return data to the UI. Your Event procedure code should be rather brief and the functions should have a single purpose.
Keep your database objects local to the method. This way you can have better control. The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
I leave it to you to add validation code. Checking for empty TextBox or no return of records.
I hope this serves as a quick introduction to using ADO.net. The take away is:
Use Parameters
Make sure connections are closed. (Using blocks)
Private ConnString As String = "server=ip of server; username=; password=; database="
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim GroupID As String = GetGroupID(TextBox1.Text)
If GroupID = "4" Then
'your code here
End If
Dim LocalTable As DataTable = GetLicenseKeysData(TextBox1.Text)
'Get the count
Dim RowCount As Integer = LocalTable.Rows.Count
'Display the data
DataGridView1.DataSource = LocalTable
End Sub
Private Function GetGroupID(InputName As String) As String
'Are you sure member_group_id is a String? Sure looks like it should be an Integer
Dim member_group_id As String = ""
'You can pass the connection string directly to the constructor of the connection
Using MysqlConn As New MySqlConnection(ConnString)
'If you only need the value of one field Select just the field not *
'ALWAYS use parameters. See comment by #djv concerning drop table
Using cmd As New MySqlCommand("SELECT g_id FROM core_members where name= #Name")
'The parameters are interperted by the server as a value and not executable code
'so even if a malicious user entered "drop table" it would not be executed.
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = InputName
MysqlConn.Open()
'ExecuteScalar returns the first column of the first row of the result set
member_group_id = cmd.ExecuteScalar.ToString
End Using
End Using
Return member_group_id
End Function
Private Function GetLicenseKeysData(InputName As String) As DataTable
Dim dt As New DataTable
Using cn As New MySqlConnection(ConnString)
Using cmd As New MySqlCommand("SELECT * FROM `nexus_licensekeys` where lkey_key= #Name;", cn)
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = InputName
cn.Open()
dt.Load(cmd.ExecuteReader())
End Using
End Using
Return dt
End Function

How to retrieve data from mysql to a datagridview that contains an image column?

I tried retrieving data from MySQL to datagridview. The table contains an image column. When I remove the image column, the code works fine but it doesn't seem to work with the image column included.
Here's my code.
Mda= new mysldataadapter ("select * from user_info", con)
Dt = new datatable
Mda.fill(dt)
With datagridview1
. Datasource =dt
End with
I get this error msg
Datagridview default error dialog
System.argumentexception: parameter is not valid at
system.drawing.image.fromstream(....
Try using MemoryStream to store the image then show it... something like this :
Dim command As New MySqlCommand("SELECT `id`, `pic` FROM `mytb` WHERE `id` = #ID", connection)
command.Parameters.Add("#ID", MySqlDbType.UInt64).Value = TextBoxID.Text
Dim Adapter As New MySqlDataAdapter(command)
Dim DBTable As New DataTable()
Try
Adapter.Fill(DBTable)
Dim imgByte() As Byte
If DBTable.Rows.Count = 1 Then
imgByte = DBTable(0)(1)
Dim MS As New MemoryStream(imgByte)
PictureBox1.Image = Image.FromStream(MS)
End If
Catch ex As Exception
MessageBox.Show("ERROR")
PictureBox1.Image = Nothing
End Try
NOTE : The data type for the column must be BLOB.
Feel free to ask about anything you don't understand.
Hope that was helpful.

VB.NET: showing DATE in datagridview bound in a database error

I bind table A from mySQL database to a datagridview. One of its columns is "in_Date" with data type DATE(). An exception says
String was not recognized as valid DateTime.Couldn't <> store in
in_Date column. Expected type is DateTime.
Here's my code in connection:
Dim myconn as MySqlConnection = New MySqlConnection
myconn.ConnectionString = "server=localhost; userid=root; password=pw; database=db"
Dim adapter As MySqlDataAdapter = New MySqlAdapter
Dim table As DataTable = New DataTable
Dim bind As New BindingSource
myconn.Open()
Dim command as MySqlCommand ("select * from db.A;")
adapter.SelectCommand = command
adapter.Fill(table)
bind.DataSource = table
MyDGV.DataSource = bind
adapter.Update(table)
myConn.close()
The table is yet empty. It was fine before when my columns are only in either varchar or int data types. How can I do that with DATE? I don't know what is the problem and how I can solve it. Thank you in advance.

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