I want to display the data based on the value of the desired user, I tried to use a parameter that contains the value from the input. When I run the program data can not be performed. I'm trying to find my fault location code, by checking the value of limit_kar that holds the result of input from the user are the contents of the corresponding results of the input, when the limit_kar value stored into parameter changed to 0, I think a lot of errors in my code, please suggesting that the problem this can be resolved
I'm using VS 2008 and mysql
thank you
Newbie
this is mycode
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
sql = "SELECT NoReg,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.Int64)).Value = **limit_kar**
dreader = cmd.ExecuteReader
If dreader.HasRows Then
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
Else
MsgBox("Not Found")
End If
myconnection.close()
Return tmpBaca
'dreader.Close()
End Function
The syntax of your parameter declaration is incorrect. Look at the example here : http://www.devart.com/dotconnect/mysql/docs/Parameters.html.
cmd.Parameters.Add(New MySqlParameter("?fn", MySqlDbType.Int64)).Value = limit_kar
This looks odd to me. Shouldn't Add take the value as parameter ? What is "?fn" ? Does Add really return the new MysqlParameter instance ?
The following sticks to the example from the docs. I still don't understand the reason why you are using ?fn and why you declare the type explicitly as MySqlDbType.Int64.
sql = "SELECT NoReg,status_kartu FROM tb_stock WHERE status= '0' and status_kartu= '0' ORDER BY NoReg ASC Limit ?"
cmd = New MySqlCommand(sql, myconnection.open)
cmd.Parameters.Add("limit_kar", limit_kar)
Related
i want to set a data source to my combobox when i run there s no error but it keeps showing zeros in the combobox
Dim cnx As New MySqlConnection("datasource=localhost;database=bdgeststock;userid=root;password=")
Dim cmd As MySqlCommand = cnx.CreateCommand
Dim da As MySqlDataAdapter
Dim ds As New DataSet
If ConnectionState.Open Then
cnx.Close()
End If
cnx.Open()
cmd.CommandText = "SELECT idf,(prenom + ' ' + nom) AS NAME FROM fournisseur "
da = New MySqlDataAdapter(cmd)
cnx.Close()
da.Fill(ds)
da.Dispose()
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.ValueMember = "idf"
ComboBox1.DisplayMember = "NAME"
For ComboBox data source you probably don't need heavy Data Set or DataTable - collection of plain object will do the job.
Another approach would be to move representation logic to the vb.net code and leave sql server to do persistence logic only.
Public Class Fournisseur
Public ReadOnly Property Id As Integer
Public ReadOnly Property Name As String
Public Sub New(id As Integer, prenom As String, nom As String)
Id = id
Name = $"{pronom} {nom}".Trim()
End Sub
End Class
You can create dedicated function to load data
Private Function LoadItems() As List(Of Fournisseur)
Dim query = "SELECT idf, prenom, nom FROM fournisseur"
Using connection As New MySqlConnection(connectionString)
Using command As New MySqlCommand(query, connection)
connection.Open()
Dim items = new List(Of Fournisseur)()
Using reader AS MySqlDataReader = command.ExecuteReader()
While reader.Read()
Dim item As New Fournisseur(
reader.GetInt32(0),
reader.GetString(1),
reader.GetString(2)
)
items.Add(item)
End While
End Using
Return items
End Using
End Using
End Function
Then usage will look pretty simple
ComboBox1.ValueMember = "Id"
ComboBox1.DisplayMember = "Name"
ComboBox1.DataSource = LoadItems()
I think the problem is in your sql, and mysql is performing some sort of numeric addition on prenom plus nom and producing 0
Try
CONCAT(prenom, ' ', nom) as name
In your sql instead. I prefer using concat in most RDBMS for concatenating strings because is is more consistent with its behaviour on NULLs - in sqlserver, using the concat operator of plus on something like 'a' + null results in NULL but in oracle 'a' || null is a - in both the CONCAT behaviour is consistent
Here's a full code with all my recommendations:
Dim cnstr = "datasource=localhost;database=bdgeststock;userid=root;password="
Dim cmd = "SELECT idf, CONCAT(prenom, ' ', nom) AS nom FROM fournisseur "
Using da As New MySqlDataAdapter(cmd, cnstr)
Dim dt As New DataTable
da.Fill(dt)
ComboBox1.DataSource = dt
ComboBox1.ValueMember = "idf"
ComboBox1.DisplayMember = "nom"
End Using
Tips:
you don't need to mess around with the connection: dataadapter will create/open/close it for you
use a datatable not a dataset
use Using
use the constructor of MySqlDataAdapter that takes a connectionstring and a command text- shorter and nearer in this case. I only use the constructor that takes a DbConnection if I'm manually enrolling multiple commands in a transaction etc
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
The error message is also available in another threads but in my case it's different.
Object reference not set to an instance of an object. When querying the following select statement. What is the problem inside?
Dim con As New MySqlConnection(ConString)
Dim sql As String
Dim idno As Integer
sql = "select client_id from car_rent where car_id = #carid"
cmd.Parameters.AddWithValue("#carid", carid.Text.Trim)
cmd = New MySqlCommand(sql, con)
idno = cmd.ExecuteScalar()
If (idno > 0) Then
MsgBox("The Car is already Rented!", MsgBoxStyle.Exclamation, "Car Rental System")
Return
End If
I don't see you opening the connection anywhere. use
con.open()
Switch the order of these two lines
cmd = New MySqlCommand(sql, con)
cmd.Parameters.AddWithValue("#carid", carid.Text.Trim)
Also the line in which you execute the command seems to be working because you are using Option Strict Off, and I suggest to change to Option Strict On. In the short term you have to solve many problems but it allows better coding practices
idno = CType(cmd.ExecuteScalar(), Integer)
However, if the command above doesn't find any record matching the parameter passed, ExecuteScalar returns Nothing and so you need to test for this situation
Dim result = cmd.ExecuteScalar()
if result IsNot Nothing Then
idno = CType(result, Integer)
And, of course, the connection should be opened before, so summarizing everything
Dim sql = "select client_id from car_rent where car_id = #carid"
Using con As New MySqlConnection(ConString)
Using cmd = New MySqlCommand(sql, con)
con.Open()
cmd.Parameters.AddWithValue("#carid", carid.Text.Trim)
Dim result = cmd.ExecuteScalar()
if result IsNot Nothing Then
Dim idno = CType(result, Integer)
If (idno > 0) Then
MsgBox("The Car is already Rented!", MsgBoxStyle.Exclamation, "Car Rental System")
Return
End If
End If
End Using
End Using
Well probably is enough to test for Nothing on the result of ExecuteScalar to take your decision unless you need the idno variable for other purposes.
I have run into this error while collecting data from a mysql database and placing it into a DataView control... This is my code:
Private Function PopulateActivity()
Dim loginStatement As String = "SELECT * FROM activity WHERE id = #userid"
Dim cmd As MySqlCommand = New MySqlCommand(loginStatement, mainconn)
cmd.Parameters.AddWithValue("#userid", LoggedInUser.ID)
Dim drMyAcount As MySqlDataReader = cmd.ExecuteReader()
Dim rowCount As Integer = 0
Dim rowAmount As Integer = 0
'gets count of rows returned from mysql query'
Using dt As New DataTable
dt.Load(drMyAcount)
rowAmount = dt.Rows.Count
End Using
'adds an entry for each item returned from the mysql query'
Do While rowCount < rowAmount
drMyAcount.Read() 'HERE IS WHERE ERROR OCCURS'
Dim tempDateTime As String = drMyAcount.Item("dateTime")
Dim tempInfo As String = drMyAcount.Item("info")
Dim tempBalChanges As String = drMyAcount.Item("balChange")
Dim tempToFrom As String = drMyAcount.Item("toFrom")
ActivityView.Rows.Add(tempDateTime, tempInfo, tempBalChanges, tempToFrom)
rowCount = rowCount + 1
Loop
drMyAcount.Close()
Return 0
End Function
I am unaware of why this is but it gives me an 'Invalid Attempt to Read when reader is closed' error one the:
drMyAccount.Read()
line...
I would appreciate any help on this topic! Thanks Much...
take out the dt.Load() , and counting of the rows prior to using datareader. DataReader has a built in property of .HasRows
if (drMyAcount.HasRows)
while (drMyAcount.Read())
Dim tempDateTime As String = drMyAcount.Item("dateTime")
Dim tempInfo As String = drMyAcount.Item("info")
Dim tempBalChanges As String = drMyAcount.Item("balChange")
Dim tempToFrom As String = drMyAcount.Item("toFrom")
ActivityView.Rows.Add(tempDateTime, tempInfo, tempBalChanges, tempToFrom)
rowCount = rowCount + 1 //you can still count rows in the loop
Loop
The MSDN documentation does not seem to specify, but apparently the DataTable.Load method closes the given IDataReader when it is done loading the data into the table. So, once you call dt.Load(drMyAcount), the drMyAcount will be closed.
Could anyone help me with the following WHERE statement ? I want to make bn as reference in WHERE statement.
This is whats in my code:
Public bn As String = ""
Dim SQLStatement As String = "UPDATE patient SET number_of_bottles='" & lblBottle.Text & "' WHERE bednumber=bn ORDER BY patient_ID DESC LIMIT 1"
During the program, bn is an identifier where I would know which bednumber I will gonna access.
Any help would be appreciated thanks!
(Edited to use MySQL-specific objects rather than generic ODBC)
Dim bn As String = "" ' Set this to some value in your code
Dim bottles As Integer = 0 ' Set this to some value in your code
Dim SQLStatement As String = "UPDATE patient SET number_of_bottles = #bottles WHERE bednumber = #bednumber"
Using cnn As New MySqlConnection("Connection string here")
Dim cmd As New MySqlCommand(SQLStatement, cnn)
cmd.Parameters.AddWithValue("bottles", bottles)
cmd.Parameters.AddWithValue("bednumber", bn)
cnn.Open()
cmd.ExecuteNonQuery()
cnn.Close()
End Using
Alternate version, creating MySqlParameter objects by hand -- note that you'll need to create the parameter objects, set their values, then add them to the parameters collection of the MySqlCommand object
Using cnn As New MySqlConnection("Connection string here")
Dim cmd As New MySqlCommand(SQLStatement, cnn)
Dim pBottles As New MySqlParameter("bottles", bottles)
Dim pBedNumber As New MySqlParameter("bednumber", bn)
cmd.Parameters.Add(pBottles)
cmd.Parameters.Add(pBedNumber)
cnn.Open()
cmd.ExecuteNonQuery()
cnn.Close()
End Using