Sql Select Data Mysql Error - mysql

Newbie want to ask
I want to display the data based on the limit input by the user,
example: user enter a value of 100, and the data will appear as 100.
limit value is always changing according to the value in the input by the user
but there is a problem You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near'' 100'' at line 1.
please help to resolve this problem ..
thank you
Public Function Tampil_Stock(ByVal limit_kar As String) As List(Of Class_stock)
Dim tmpBaca As New List(Of Class_stock)
Dim cmd As New MySqlCommand
Dim dreader As MySqlDataReader
Dim ds As New DataSet
Dim sql As String
Try
sql = "SELECT NoReg,status,status_kartu FROM tb_stock WHERE status= '0' and status_kartu= '0' ORDER BY NoReg ASC limit ?fn"
cmd = New MySqlCommand(sql, myconnection.open)
cmd.Parameters.Add(New MySqlParameter("?fn", MySqlDbType.String, 10)).Value = limit_kar
dreader = cmd.ExecuteReader
While dreader.Read
Dim objTemp As New Class_stock
objTemp.NoReg_ = dreader.Item("NoReg")
'objTemp.NoPin_ = dreader.Item("NoPin")
objTemp.status_ = dreader.Item("status")
objTemp.status_kartu_ = dreader.Item("status_kartu")
tmpBaca.Add(objTemp)
End While
Catch sqlex As MySqlException
Throw New Exception(sqlex.Message.ToString())
End Try
myconnection.close()
Return tmpBaca
'dreader.Close()
End Function
Insert data in listview
Sub Loadlist (Optional ByVal criteria As Integer = 0)
Dim objList As List (Of Class_stock)
As String Dim nourut
objList = stock.Tampil_Stock (criteria)
nourut = 1
Me.ListView1.Items.Clear ()
For i As Integer = 0 To objList.Count - 1
nourut = ListView1.Items.Count + 1
Me.ListView1.Items.Add (nourut)
Me.ListView1.Items (i). SubItems.Add (objList.Item (i). NoReg_)
Next
end Sub

limit_kar should be an integer, you used string. Also changed the parameter to integer instead of string.
Public Function Tampil_Stock(ByVal limit_kar As Integer) As List(Of Class_stock)
Dim tmpBaca As New List(Of Class_stock)
Dim cmd As New MySqlCommand
Dim dreader As MySqlDataReader
Dim ds As New DataSet
Dim sql As String
Try
sql = "SELECT NoReg,status,status_kartu FROM tb_stock WHERE status= '0' and status_kartu= '0' ORDER BY NoReg ASC limit ?fn"
cmd = New MySqlCommand(sql, myconnection.open)
cmd.Parameters.Add(New MySqlParameter("?fn", MySqlDbType.Int)).Value = limit_kar
dreader = cmd.ExecuteReader
While dreader.Read
Dim objTemp As New Class_stock
objTemp.NoReg_ = dreader.Item("NoReg")
'objTemp.NoPin_ = dreader.Item("NoPin")
objTemp.status_ = dreader.Item("status")
objTemp.status_kartu_ = dreader.Item("status_kartu")
tmpBaca.Add(objTemp)
End While
Catch sqlex As MySqlException
Throw New Exception(sqlex.Message.ToString())
End Try
myconnection.close()
Return tmpBaca
'dreader.Close()
End Function

Related

AddWithValue MySqlType.Decimal

Unfortunately, I can't get any further. Working with vs2019 and vb. Created a cascading DropDownList (country, state, region). It works perfectly for country where I don't have to use AddWithValue (where). With state where I have to use AddWithValue (where), I don't get it baked. All IDs are defined as integers. The relevant code:
Protected Sub idLand_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
DropDownBundesland.Items.Clear()
DropDownBundesland.Items.Add(New ListItem("--Select Country--", ""))
DropDownRegion.Items.Clear()
DropDownRegion.Items.Add(New ListItem("--Select City--", ""))
DropDownBundesland.AppendDataBoundItems = True
Dim strConnString As [String] = ConfigurationManager _
.ConnectionStrings("conString").ConnectionString
Dim strQuery As [String] = "Select Bundesland, idBundesland, idLand from Campingplatz ORDER BY Bundesland ASC where idLand = #LandID Group BY Bundesland"
Dim con As New MySqlConnection(strConnString)
Dim cmd As New MySqlCommand()
cmd.Parameters.AddWithValue("#LandID", MySqlDbType.Decimal).Value = DropDownLand.SelectedItem.Value
cmd.CommandType = CommandType.Text
cmd.CommandText = strQuery
cmd.Connection = con
Try
con.Open()
DropDownBundesland.DataSource = cmd.ExecuteReader()
DropDownBundesland.DataTextField = "Bundesland"
DropDownBundesland.DataValueField = "idBundesland"
DropDownBundesland.DataBind()
If DropDownBundesland.Items.Count > 1 Then
DropDownBundesland.Enabled = True
Else
DropDownBundesland.Enabled = False
DropDownRegion.Enabled = False
End If
Catch ex As Exception
'Throw ex
Finally
con.Close()
con.Dispose()
End Try
End Sub
Please help!
this query is wrong:
Dim strQuery As [String] = "Select Bundesland, idBundesland, idLand from Campingplatz ORDER BY Bundesland ASC where idLand = #LandID Group BY Bundesland"
you must change the order of WHERE, ORDER BY and GROUP BY like:
Dim strQuery As [String] = "Select Bundesland, idBundesland, idLand from Campingplatz WHERE idLand = #LandID Group BY Bundesland ORDER BY Bundesland ASC"
Here you can see the Ssyntax: https://mariadb.com/kb/en/select/
I don't like to mix user interface code with database code. The database code should be independent of the kind of application where it is used.
Connections, Commands and DataReaders need to have their Dispose methods called so they can release unmanaged resources. You are provided with Using...End Using blocks to accomplish this and also close the connection.
You are mixing apples and oranges building the parameters collection. I showed both Add and AddWithValue in the code.
Please see my notes in the Catch block.
I would make the strConString a class level variable if the database is accessed by any other methods in the class.
Protected Sub idLand_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
DropDownBundesland.Items.Clear()
DropDownBundesland.Items.Add(New ListItem("--Select Country--", ""))
DropDownRegion.Items.Clear()
DropDownRegion.Items.Add(New ListItem("--Select City--", ""))
DropDownBundesland.AppendDataBoundItems = True
Dim dt As DataTable = Nothing
Try
dt = GetDropDownData(CDec(DropDownLand.SelectedItem.Value))
Catch ex As Exception
'Where would you be throwing it to? This is an event procedure so is not "called"
'Alert the user, maybe log the error
Exit Sub
End Try
DropDownBundesland.DataSource = dt
DropDownBundesland.DataTextField = "Bundesland"
DropDownBundesland.DataValueField = "idBundesland"
DropDownBundesland.DataBind()
If DropDownBundesland.Items.Count > 1 Then
DropDownBundesland.Enabled = True
Else
DropDownBundesland.Enabled = False
DropDownRegion.Enabled = False
End If
End Sub
Private strConnString As [String] = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Private Function GetDropDownData(LandID As Decimal) As DataTable
Dim dt As New DataTable
Dim strQuery As [String] = "Select Bundesland, idBundesland, idLand
From Campingplatz
Where idLand = #LandID
Group BY Bundesland
ORDER BY Bundesland ASC "
Using con As New MySqlConnection(strConnString),
cmd As New MySqlCommand(strQuery, con)
cmd.Parameters.Add("#LandID", MySqlDbType.Decimal).Value = LandID
'or cmd.Parameters.AddWithValue("#LandID", LandID)
con.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function

VB.Net Function Return MySql Results Two Dimensional Array

The following code pulls data from a MySql connection and returns the array (output).
This two dimensional array only works when the number of rows and columns are specified before running the query.
Is there a way to get around this? A non-fixed array size?
Please help!
Public Function GetUsers() As String(,)
Dim GetCommand As MySqlCommand
Dim SQL As String = "Select * From users"
Dim output(,) As String
Dim intRowCount As Integer = 2
Dim intColumnCount As Integer = 3 ' Users Count
ReDim output(intColumnCount - 1, intRowCount - 1)
Dim GetMyConn As New MySqlConnection
GetMyConn.ConnectionString = "server = mysql.com;user id=rtest;password=test1234;database=rtestdb;"
GetMyConn.Open()
GetCommand = New MySqlCommand(SQL, GetMyConn)
Dim counter As Integer = 0
Try
Dim getResult As Object = GetCommand.ExecuteReader()
While getResult.Read()
output(counter, 0) = getResult("username").ToString()
output(counter, 1) = getResult("game_ip").ToString()
counter = counter + 1
End While
Catch e As MySqlException
MessageBox.Show("There was an error accessing your data. DETAIL: " & e.ToString())
End Try
GetMyConn.Close()
Return output
End Function
'''
Use this instead
output(counter, 0) = getResult.GetString(0)
output(counter, 1) = getResult.GetString(1)
When you have integer use
reader.GetInt32(0)
and so on
To get the correct dimensions for your array
Change your select statement like below
Dim SQL As String = "Select (SElECT Count(*) rowcount FROM users),* From users"
So you have in your result table a column more with the row count in every row.
Now to redim your array. the Columncount you should know. Else you have to add also
,(SELECT count(*) FROM information_schema.columns
WHERE table_name ='users') columncount
So and then you have to adept your datareader
Try
Dim getResult As Object = GetCommand.ExecuteReader()
If getResult.Read() Then
ReDim output(intColumnCount - 1, Integer.Parse(getResult("rowcount ")) - 1)
output(0, 0) = getResult("username").ToString()
output(0, 1) = getResult("game_ip").ToString(
counter += 1
While getResult.Read()
output(counter, 0) = getResult("username").ToString()
output(counter, 1) = getResult("game_ip").ToString()
counter = counter + 1
End While
END IF
Catch e As MySqlException
MessageBox.Show("There was an error accessing your data. DETAIL: " & e.ToString())
End Try
The idea is to get the first row, catch rowcount and redimension the array properly with the right diemnsions. As described you can if you want do the same with with thecoumnsnumber, if you want to be even more flexible.
I have given three different options using different data structures. Most databse objects need to be closed and disposed. Using...End Using blocks take care of this. You want to do as little as possible while the connection is open.
'Option 1 Using DataTable
Public Function GetUsers() As DataTable
Dim dt As New DataTable
Using GetMyConn As New MySqlConnection("server = mysql.com;user id=rtest;password=test1234;database=rtestdb;"),
GetCommand As New MySqlCommand("Select * From users", GetMyConn)
GetMyConn.Open()
dt.Load(GetCommand.ExecuteReader)
End Using
Return dt
End Function
'Option 2 Using List(Of User)
Public Class User
Public Property ID As Integer
Public Property Name As String
Public Property GameIP As String
Public Sub New(UserID As Integer, UName As String, UGame As String)
ID = UserID 'Assumed there was a primary key ID of some sort
Name = UName
GameIP = UGame
End Sub
End Class
Public Function GetUsers() As List(Of User)
Dim lst As New List(Of User)
Using GetMyConn As New MySqlConnection("server = mysql.com;user id=rtest;password=test1234;database=rtestdb;"),
GetCommand As New MySqlCommand("Select * From users", GetMyConn)
GetMyConn.Open()
Using r = GetCommand.ExecuteReader
While r.Read
Dim u = New User(r.GetInt32(0), r.GetString(1), r.GetString(2))
lst.Add(u)
End While
End Using
End Using
Return lst
End Function
'Option 3 Using 2D array
Public Function GetUsers() As String(,)
Dim Users(,) As String = Nothing
Dim dt As New DataTable
Using GetMyConn As New MySqlConnection("server = mysql.com;user id=rtest;password=test1234;database=rtestdb;"),
GetCommand As New MySqlCommand("Select username, game_ip From users", GetMyConn)
GetMyConn.Open()
dt.Load(GetCommand.ExecuteReader)
End Using
ReDim Users(dt.Rows.Count - 1, 1)
For r = 0 To dt.Rows.Count - 1
Users(r, 0) = dt(r)(0).ToString
Users(r, 1) = dt(r)(1).ToString
Next
Return Users
End Function
The easiest way is:
Friend Function getDataAsArray() As Array
Try
Dim SQLConnection = New SqlConnection("server = mysql.com;user id=rtest;password=test1234;database=rtestdb;")
Dim DtTable As New DataTable
Dim mSqlAdapter As New SqlClient.SqlDataAdapter With {
.SelectCommand = New SqlCommand("Select * From yourtable", SQLConnection)
}
mSqlAdapter.Fill(DtTable)
Dim output As Array = (From twoColumns As DataRow In DtTable
Select col1 = twoColumns.Item("username"),
col2 = twoColumns.Item("game_ip")).ToList.ToArray
Return output
Catch ex As Exception
Console.WriteLine("Ops ops ops something wrong: " + ex.ToString)
End Try
Return Nothing
End Function

My application outputs DBNull but in the database it isn't DBNull

My application outputs "System.InvalidCastException: "Object cannot be cast from DBNull to other types."
Dim sqlquery = String.Format("SELECT id, date, film, start_time, end_time, participants_count, confirmed FROM calendar WHERE id='" & id & "'")
connection.Open()
With command
.Connection = connection
.CommandText = sqlquery
End With
dataadapter.SelectCommand = command
dataadapter.Fill(datatable)
id = Convert.ToInt32(datatable.Rows(0).Item("id"))
Dim date_ As String = datatable.Rows(0).Item("date").ToString
Dim film As String = datatable.Rows(0).Item("film").ToString
Dim start_time As String = datatable.Rows(0).Item("start_time").ToString
Dim end_time As String = datatable.Rows(0).Item("end_time").ToString
Dim participants_count As Integer = Convert.ToInt32(datatable.Rows(0).Item("participants_count"))
Dim confirmed As Integer = Convert.ToInt32(datatable.Rows(0).Item("confirmed"))
The problem arises there: "participants_count" and "confirmed". All the other columns are working perfectly. In the database these two columns aren't DBNull: Picture of the real MySQL-Result. They can't even be DBNull: MySQL Structure
If I output the value of both with a MessageBox it also contains nothing.
I would be very grateful if I became a solution.
Julius
Dim participants_count As Integer
Integer.TryParse(datatable.Rows(0).Item("participants_count").Tostring, participants_count)
This will attempt to convert it to an Integer and returns 0 if it fails otherwise it will set the value to participants_count. This should help with the DBNull issue. You can do this with the confirmed field to.
You can get the query results without using a DataTable. That way you can be exact about the data types and so there is less chance of something unexpected happening:
Dim connStr = "your connection string"
Dim sql = "SELECT `id`, `date`, `film`, `start_time`, `end_time`, `participants_count`, `confirmed` FROM `calendar` WHERE `id` = #id"
Dim id = "2"
Dim date_ As DateTime
Dim start_time As TimeSpan
Dim end_time As TimeSpan
Dim participants_count As Integer
Dim confirmed As Boolean
Using conn As New MySqlConnection(connStr)
Using cmd As New MySqlCommand(sql, conn)
cmd.Parameters.Add(New MySqlParameter With {
.ParameterName = "#id",
.MySqlDbType = MySqlDbType.VarChar,
.Size = 8,
.Value = id})
conn.Open()
Dim rdr = cmd.ExecuteReader()
If rdr.HasRows Then
date_ = rdr.GetDateTime(1)
start_time = rdr.GetTimeSpan(3)
end_time = rdr.GetTimeSpan(4)
participants_count = rdr.GetInt16(5)
confirmed = rdr.GetBoolean(6)
End If
conn.Close()
End Using
End Using
The SQL parameter should have its .MySqlDbType and .Size set to match the id column in the database. The rdr.Get... functions should be chosen to match the types from the database.

select columns with not null property

I am looking for a way to select columns with a not null property and store it on to an ArrayList.
I have searched many threads for an answer but no luck.
I created a function which allows me to read data from a table but the problem is I don't know how do I get it to read the column name with a not null property. Here is the code that I tried
Public Function getNull(ByVal table As String) As ArrayList
Dim col_names As String = New String(getNames(table))
Dim nullColumns As ArrayList = New ArrayList
Dim dtreader As MySqlDataReader
Dim conn As MySqlConnection
Dim strConn As String
strConn = withDatabase
conn = New MySqlConnection(strConn)
Try
Dim cmd = New MySqlCommand("SELECT * FROM " & table & " WHERE " & col_names & " IS NOT NULL", conn)
conn.Open()
dtreader = cmd.ExecuteReader()
While dtreader.Read
'Get column names with not null property'
End While
Catch ex As Exception
MsgBox("Error " + ex.ToString, MsgBoxStyle.Critical)
End Try
Return nullColumns
End Function
Public Function getNames(ByVal table As String) As String
Dim conn As MySqlConnection
Dim strConn As String
Dim names As New String("")
strConn = withDatabase
conn = New MySqlConnection(strConn)
Using conn
conn.Open()
Dim dt = conn.GetSchema("Columns", New String() {Nothing, Nothing, table})
For Each row In dt.Rows
names += row("COLUMN_NAME") + " AND "
Next
names = names.Remove(names.Length - 4)
End Using
conn.Close()
Return names
End Function
The other threads I found was to find null values in a column, which is not I was looking for.

Save Datagridview if it is Checked by CheckboxColumn

Hello Everyone Good Afternoon,
I have an Object in a form and they are Datagridview1 and a Save Button the Datagridview1 will populate data from my Database on Form_Load and the Data will show with a Corresponding Checkbox. Like the Image below
and If you here is the code for that
Private Sub loadtech()
Dim con1 As MySqlConnection = New MySqlConnection("datasource=localhost;database=operations;userid=root;password=admin1950;Convert Zero Datetime=True")
Dim sql1 As MySqlCommand = New MySqlCommand("select TechName from technicians order by Category ASC", con1)
Dim ds1 As DataSet = New DataSet
Dim adapter1 As MySqlDataAdapter = New MySqlDataAdapter
con1.Open()
adapter1.SelectCommand = sql1
adapter1.Fill(ds1, "MyTable")
DataGridView1.DataSource = ds1.Tables(0)
con1.Close()
With DataGridView1
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "Technician / Electrician"
End With
DataGridView1.Columns.Item(0).Width = 150
DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
Me.DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True
Me.DataGridView1.Columns(0).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
Dim checkBoxColumn As New DataGridViewCheckBoxColumn()
checkBoxColumn.HeaderText = "Tag"
checkBoxColumn.Width = 30
checkBoxColumn.Name = "checkBoxColumn"
DataGridView1.Columns.Insert(0, checkBoxColumn)
End Sub
and my Question is how can I save the Checked Row in Database? Lets say I checked all of it so the Rows will be saved in Database. (Regardless of How many I Checked)
Here is my code but its not working. :(
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conn As MySqlConnection = New MySqlConnection("datasource=localhost;database=operations;userid=root;password=admin1950;Convert Zero Datetime=True")
conn.Open()
Dim comm As MySqlCommand = New MySqlCommand()
comm.Connection = conn
Dim name As String
For i As Integer = 0 To Me.DataGridView1.Rows.Count
name = Me.DataGridView1.Rows(0).Cells(1).Value
comm.CommandText = "insert into assignments(ElecAssigned) values('" & name & "')"
comm.ExecuteNonQuery()
Next
conn.Close()
End Sub
TYSM For future help
Yes, your loop is slightly incorrect. Try using this loop and see if that fixes your issue. The issue, you didn't use the i variable. It should be placed in Row(i) and you were looping from 0 to Count when it should be 0 to Count - 1
Dim name As String
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1 Step 1
If Me.DataGridView1.Rows(i).Cells(0).Value = True Then
name = Me.DataGridView1.Rows(i).Cells(1).Value
comm.CommandText = "insert into assignments(ElecAssigned) values('" & name & "')"
comm.ExecuteNonQuery()
End If
Next