Please help, how do I really use data reader in vb.net. I'm using odbc to connect mysql and vb.net.
Function I declared on a module:
Public Function form2search(ByVal drugname As String) As OdbcDataReader
cmd.CommandText = "SELECT * FROM drug WHERE Drug_name LIKE'%" & drugname & "' "
Return cmd.ExecuteReader
End Function
text_changed event:
con.drugname=textBoxdrugname.text
Dim rdr As Odbc.OdbcDataReader
rdr = con.form2search(drugname)
if rdr.hasrows=true then
rdr.read()
TextBoxdrugname.Text = rdr("Drug_name").ToString
TextBoxdrugcode.Text = rdr("Drug_code").ToString
drugtype.Text = rdr("Drug_type").ToString
end if
I see a result, but it only loads the first item on the database. I've put this code in the text_changed event. What's the proper way of doing this? And what's wrong with the 2nd code, why is it only loading the first data
As you can see the con is the module where I declared the function. Then I created an object of it in the form.
The DataReader is a low level implementation that does not support navigation and only reads a single row every time you call
reader.Read()
For a Windows Forms app you probably should use a DataSet / DataTable approach or a ORM. And you should consider using the mysql connector net over the odbc driver. It is available at mysql.com.
Here is a little demo code:
dim table as new DataTable("table1")
' Create a Connection
using conn as new MysqlConnection("...connectionstring")
conn.Open() ' Open it
' Create a new Command Object
using cmd as new MysqlCommand("SELECT * FROM table", conn)
' Create a DataAdapter
' A DataAdapter can fill a DataSet or DataTable
' and if you use it with a CommandBuilder it also
' can persist the changes back to the DB with da.Update(...)
using da as new MysqlDataAdapter(cmd)
da.Fill(table) ' Fill the table
end using
end using
end using
' A Binding Source allows record navigation
dim bs as new BindingSource(table, nothing)
' You can bind virtually every property (most common are "text" "checked" or "visible"
' of a windows.forms control to a DataSource
' like a DataTable or even plain objects
textBox1.DataBindings.Add("Text", bs, "columnName")
' Now you can navigate your data
bs.MoveNext()
' Even a ComboBox can be bound to a List and display the related value
' of your current row
comboBox1.DataSource = table2
comboBox1.DisplayMember = "name"
comboBox1.ValueMember = "id"
comboBox1.DataBindings.Add("SelectedValue", bs, "id")
You have to just put the object of data reader in while loop.Here is the sample code:
dr = myCommand.ExecuteReader()
While dr.Read()
'reading from the datareader
MessageBox.Show("colname1" & dr(0).ToString())
MessageBox.Show("colname2" & dr(1).ToString())
MessageBox.Show("colname3" & dr(2).ToString())
MessageBox.Show("colname4" & dr(3).ToString())
MessageBox.Show("colname5" & dr(4).ToString())
'displaying the data from the table
End While
dr.Close()
Related
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
I have a MySQL database with the columns TIME and METHOD, which have about 15,000+ rows of data. I need to get these columns/rows to display on a DataGridView within a vb.net form. I am using the MySql.Data.dll to connect to the database and run my queries. Below is my current code:
Private Sub RetreiveData() Handles Button.click
Dim dt As New DataTable
Dim connectionString As String = "server=ipaddress;database=debugging;user id=root;password=password;port=3307"
Dim connection As MySqlConnection = New MySqlConnection(connectionString)
Try
connection.Open()
Dim sql As String = String.Format("SELECT time, method FROM test1 WHERE custPin='{0}' AND dataID='{1}' ORDER BY TIME;", customerPin, sessionID)
Dim dAdapter As MySqlDataAdapter = New MySqlDataAdapter(Sql, connection)
dAdapter.Fill(dt)
Catch ex As Exception
MessageBox.Show("ERROR: " & ex.Message & Environment.NewLine & ex.StackTrace & Environment.NewLine)
If connection.State = ConnectionState.Open Then
connection.Close()
End If
End Try
Me.dgvCustomerData.DataSource = dt
connection.Close()
End Sub
Note: "dgvCustomerData" is my DataGridView on my form, and "customerPin"/"sessionID" are retrieved from TextBoxes on my form as well.
I have checked through about 20-30 forum posts that state I should bind my data, or use different styles of data adapters, but none have been able to display my data. I can get it to create the two columns, however, no data is filled in. Any assistance would be very helpful, thanks in advanced.
I'm creating a WinService in VB.NET to get some data from a Table, do some things with these data and then upload new data into this Table.
What I need is something like this:
Dim conn As New MySqlConnection(my_connString)
conn.Open()
Dim cmd As New MySqlCommand("my_Stored_Procedure_1", conn)
cmd.CommandType = CommandType.StoredProcedure
Dim reader As MySqlDataReader = cmd.ExecuteReader()
While reader.Read()
Try
' SP to SELECT Data from DB table '
Dim columnData As String
columnData = reader("ColumnName")
columnData_2 = reader("ColumnName_2")
' (...) Do something with this Data '
Try
' SP to UPDATE Data into the same DB table '
'cmd.Dispose() '
cmd = New MySqlCommand("my_Stored_Procedure_2", conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.ExecuteReader()
' (...) Do something else '
Catch ex As Exception
Console.WriteLine("ERROR: " & ex.Message)
End Try
Catch ex As Exception
Console.WriteLine("ERROR: " & ex.Message)
End Try
End While
reader.Close()
conn.Close()
The problem is that this doesn't work. It says There is already an open DataReader associated with this Connection which must be closed first. So I tried to create different SQL commands, close and re-open the connection, and create different connections like suggested here but all of them without success. This class seems to be useful but that's a lot of code for a simple (?) task. I've read a lot of similar questions but I didn't found what I need yet.
How can I handle this issue? Some help would be nice.
This sure looks like a duplicate of the question you linked to, but the answer there doesn't provide a lot of detail on how to fix the error. As the error says, you can only have one open reader per connection, so you need to use a different connection for the update. You say you have tried that, but perhaps your attempt was incorrect. As suggested in the linked question, you should also use Using statements for resource management.
So, you probably want something like this (untested, of course!):
Try
Using conn1 As New MySqlConnection(my_connString),
conn2 As New MySqlConnection(my_connString)
conn1.Open()
conn2.Open()
Using cmd1 As New MySqlCommand("my_Stored_Procedure_1", conn1)
cmd1.CommandType = CommandType.StoredProcedure
Using reader1 As MySqlDataReader = cmd1.ExecuteReader()
While reader1.Read()
' SP to SELECT Data from DB table '
Dim columnData As String
columnData = reader1("ColumnName")
columnData_2 = reader1("ColumnName_2")
' (...) Do something with this Data '
' SP to UPDATE Data into the same DB table '
Using cmd2 As New MySqlCommand("my_Stored_Procedure_2", conn2)
cmd2.CommandType = CommandType.StoredProcedure
Using reader2 As MySqlDataReader = cmd2.ExecuteReader()
' (...) Do something else '
End Using ' reader2
End Using ' cmd2
End While
End Using ' reader1
End Using ' cmd1
End Using ' conn1, conn2
Catch ex As Exception
Console.WriteLine("ERROR: " & ex.Message)
End Try
As you can see from the levels of nesting, there is quite a lot going on here in terms of the resource scopes, so you may want to refactor this into multiple methods. You could also use a data adapter to populate a DataTable for the results of my_Stored_Procedure_1, instead of using a DataReader, and then just need a single connection (assuming the data isn't too large for that).
I have made a table in mysql with attributes Product code,Quantity,company,price. And I have created a datagridview in vb 2012 and I want to take input from the form and then display the results in a datagridview. I also want to display price from the table I have created in mysql. But, i'm not able to do so.
Here is the code of my program. plz help me
Dim row As Integer = DataGridView1.Rows.Add()
Dim connection As String
Dim command As String
Dim command2 As String
command2 = "select Company from Stock WHERE Product_Code =('" + TextBox1.Text + "');"
connection = "Data Source=localhost; Database=Entry; User Id=root; Password=;"
command = "select Price from Stock WHERE Product_Code =('" + TextBox1.Text + "');"
Dim con As New MySqlConnection(connection)
Dim cmd As New MySqlCommand(command)
Dim data As DataTable
Dim adp As New MySqlDataAdapter
Dim data2 As DataTable
Dim adp2 As New MySqlDataAdapter
DataGridView1.Rows.Item(row).Cells(0).Value = TextBox1.Text
DataGridView1.Rows.Item(row).Cells(2).Value = TextBox2.Text
Try
adp = New MySqlDataAdapter(command, connection)
adp2 = New MySqlDataAdapter(command2, connection)
data = New DataTable
data2 = New DataTable
adp.Fill(data)
adp2.Fill(data2)
DataGridView1.Rows.Item(row).Cells(1).Value = data
DataGridView1.Rows.Item(row).Cells(3).Value = data
Catch ex As Exception
MessageBox.Show("Error")
End Try
You should be able to find examples of how to do this all over SO (stack overflow). But to give you a helping hand, here are the things you need to research:
First, you should parameterize your SQL to prevent injection and readability: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
Second, you dont add rows to a datagrid, you set the datasource to something that implements IList: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.datasource.aspx Then you add items to your list if you need to. If you just want to display the rows from your table, you can set the datasource to your datatable (DATA).
Why won't this delete the data in my MySQL database!?
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim dbCon As MySqlConnection
Dim strQuery As String = ""
Dim SQLCmd As MySqlCommand
Dim DR As MySqlDataReader
Try
dbCon = New MySqlConnection("Server=Localhost;Database=myusers;Uid=root;Pwd=Mypassword")
strQuery = "DELETE settings FROM settings WHERE user=" & Me.loginuser.Text
'* FROM settings WHERE user = "Testuser"'
SQLCmd = New MySqlCommand(strQuery, dbCon)
' OPEN THE DB AND KICKOFF THE QUERY
dbCon.Open()
DR = SQLCmd.ExecuteReader
While DR.Read
req1.Text = "" And exlink.Text = ""
End While
' DONE! Close DB
DR.Close()
dbCon.Close()
Catch ex As Exception
TextBox8.Text = ("Fail" & vbCrLf & vbCrLf & ex.Message)
End Try
Here is a picture of my database:
Alternatively I could somehow make it replace what is already in the database, in which case please help me with that.
Try
strQuery = "DELETE FROM settings " _
& " WHERE user = '" & Me.loginuser.Text & "'"
but as was stated earlier, you should be using parameterized queries. If you had a user named O'Brien then your query (as composed above) would fail because of the embedded single quote. When you use DELETE, you are deleting entire records and you already specify the table name in the FROM clause.
I will try to change your code in this way
Using con = New MySqlConnection("Server=.....")
con.Open()
Dim sqlText = "DELETE * FROM settings WHERE user = #ulogin"
Using cmd = new MySqlCommand(sqlText, con)
cmd.Parameters.AddWithValue("#ulogin", Me.loginuser.Text)
cmd.ExecuteNonQuery()
End Using
End Using
First and foremost, do not use string concatenation to create command texts to pass to the database engine. In that way you risk Sql Injections, also, if the user name contains a single quote (i.e. O'Hara) your code will fail with a syntax error (Same problems arise for date formatting, parsing numeric decimals and other globalization issues). Instead a parametrized query like the one in code above will avoid all of these problems.
In a parametrized query, the text of the query doesn't contains the actual value for the search condition or the update or insert data. Instead it contains placeholders ( in our case it is called #ulogin). The correct value to insert at the placeholders position is specified using one or more MySqlParameter added to the Parameters collection of the MySqlCommand. In this case I have used the AddWithValue method that derives the correct datatype directly from the datatype of the value. Because Me.loginuser.Text is a string value then the parameter will be treated as a string value replacing incorrect single quotes and removing extraneus characters usually used to Mount Sql Injections Attacks. The engine will do the rest inserting the correct value at the placeholder at execution time
EDIT: Seeing your comment about the MySql connector used, I will try to update my answer to show a semi-equivalent version for NET 1.
Try
Dim con As MySqlConnection = New MySqlConnection("Server=.....")
con.Open()
Dim sqlText as String = "DELETE * FROM settings WHERE user = #ulogin"
Dim cmd As MySqlCommand = new MySqlCommand(sqlText, con)
Dim par As MySqlParameter = New MySqlParameter("#ulogin", MySqlDbType.VarChar)
par.Value = Me.loginuser.Text
cmd.Parameters.Add(par)
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
I am not sure if the connector 1.0.10 supports the parameter name with the # prefix or just the : prefix
i dont think you can use double quotes in mysql, i think its single quotes only. try
Query = "DELETE * FROM settings WHERE user = '" & Me.loginuser.Text & "'"