SELECT MAX(value) from table VB.net - mysql

I have this table that contains multiple values all ranging from 1 to 3000, but it keep retuning false.
What is going wrong here?
Dim connectionString As String = "Server=**; Uid=**; Pwd=**; Database=**"
Using SQLConnection As New MySqlConnection(connectionString)
Using sqlCommand As New MySqlCommand()
With sqlCommand
.CommandText = "SELECT MAX(CAST(points AS UNSIGNED)) FROM score"
.Connection = SQLConnection
.CommandType = CommandType.Text
End With
Try
SQLConnection.Open()
Using reader As MySqlDataReader = sqlCommand.ExecuteReader
While (reader.Read())
label1.Text = reader.Read()
End While
End Using
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
End Using
End Using

Probably you need to read the field not calling again Read
label1.Text = reader(0).ToString()
However, to read a scalar value like you do, it is preferable to use the ExecuteScalar method. It returns just the single value of your query without creating an MySqlDataReader and all the infrastructure needed when you want to read more than one record one by one
Using sqlCommand As New MySqlCommand()
With sqlCommand
.CommandText = "SELECT MAX(CAST(points AS UNSIGNED)) FROM score"
.Connection = SQLConnection
.CommandType = CommandType.Text
End With
Try
SQLConnection.Open()
Dim result = Convert.ToInt64(sqlCommand.ExecuteScalar())
label1.Text = result.ToString()
.....

Read() advances to the next row/result (and returns a boolean indicating if you've passed the end of the result set); you're looking for GetInt32() or similar methods.

Related

How to put two fields of database to one combobox in vb.net?

Private Sub ForgotPasswordPage1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim table2 As New DataTable
Dim cmd As New MySqlCommand
Dim cmd1 As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim da2 As New MySqlDataAdapter
Dim con = New MySqlConnection
con.ConnectionString = "server=127.0.0.1;userid=root;password=;database=pharma"
Try
'we open Connection
con.Open()
With cmd
.Connection = con
.CommandText = "SELECT `security_question_1` from pharma.account_admin where `u_name`='" & Login.u_name.Text & "';"
End With
'declare dt as new datatable
Dim dt As New DataTable
Dim dt2 As New DataTable
With sq
da.SelectCommand = cmd
'it fills the da values into dt
da.Fill(dt)
'dt provides the data surce of combobox
.DataSource = dt
'specify the what to display
.DisplayMember = "security_question_1"
'and the value
.ValueMember = "security_question_1"
End With
With cmd1
.Connection = con
.CommandText = "SELECT `security_question_2` from pharma.account_admin where `u_name`='" & Login.u_name.Text & "';"
End With
With sq
da.SelectCommand = cmd1
'it fills the da values into dt
da.Fill(dt)
'dt provides the data surce of combobox
.DataSource = dt
'specify the what to display
.DisplayMember = "security_question_2"
'and the value
.ValueMember = "security_question_2"
End With
Catch ex As Exception
Here's my code. I want to have security question 1 and security question 2, which are two different fields in my database to be inserted in a combobox.
The most important thing in my code is the use of Parameters. This change will help protect your database from malicious input. I also used an alias for security question 1 and 2. (the As Question in the select command.) Double check the data type of User Name. I guessed at varchar but it could be something else. Change the MySalDbType accordingly. Using DataTable.Load adds the records from the second query to the data table. Actually, I think the two select could be run as a Union. If you are only getting 2 questions back then I would select both questions in one query, use a datareader and add the values to the combo box manually. The Using/End Using statements ensure that objects that implement IDisosable can release their unmanaged resources as soon as posible.
Using cmd As New MySqlCommand
Using da As New MySqlDataAdapter
Using con = New MySqlConnection("server=127.0.0.1;userid=root;password=;database=pharma")
Try
With cmd
.Connection = con
.CommandType = CommandType.Text
.CommandText = "SELECT `security_question_1` As Question from pharma.account_admin where `u_name`= #UserName;"
.Parameters.Add("#UserName", MySqlDbType.VarChar).Value = Login.u_name.Text
End With
Using dt As New DataTable
da.SelectCommand = cmd
da.Fill(dt)
cmd.CommandText = "SELECT `security_question_2` As Question from pharma.account_admin where `u_name`= #UserName;"
con.Open()
Using dr As MySqlDataReader = cmd.ExecuteReader
dt.Load(dr)
con.Close()
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "Question"
ComboBox1.ValueMember = "Question"
End Using
End Using
Catch ex As Exception
End Try
End Using
End Using
End Using

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

An unhandled exception of type 'system.formatexception' occurred in mscorlib.dll in update button

When i Hit my Update button i get An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll. I'm suppose to update my database values. Only mobile number is the value that you can update.
This is the error message
Imports MySql.Data.MySqlClient
Imports System.Data.Sql
Imports System
Imports System.Data
Public Class AddStudent
Dim connString As String = "server=localhost;userid=jared;password=jared;database=database;persistsecurityinfo=True"
Dim SQLConnection As MySqlConnection = New MySqlConnection
Dim student As New DataTable()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim iReturn As Boolean
Using SQLConnection As New MySqlConnection(connString)
Using sqlCommand As New MySqlCommand()
With sqlCommand
.CommandText = "INSERT INTO students (StudentNumber, Firstname, Surname, Number) values (#sNumber,#sName,#sLname,#sNum)"
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sNumber", TextBox1sn.Text)
.Parameters.AddWithValue("#sName", TextBox1name.Text)
.Parameters.AddWithValue("#sLname", TextBox2su.Text)
.Parameters.AddWithValue("#sNum", TextBox3num.Text)
End With
Try
SQLConnection.Open()
sqlCommand.ExecuteNonQuery()
iReturn = True
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
iReturn = False
Finally
SQLConnection.Close()
End Try
End Using
End Using
End Sub
Public Function InsertStud() As Boolean
Dim iReturn As Boolean
Using SQLConnection As New MySqlConnection(connString)
Using sqlCommand As New MySqlCommand()
With sqlCommand
.CommandText = "INSERT INTO students (StudentNumber, Firstname, Surname, Number) values (#sNumber,#sName,#sLname,#sNum)"
.Connection = SQLConnection
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sNumber", TextBox1sn.Text)
.Parameters.AddWithValue("#sName", TextBox1name.Text)
.Parameters.AddWithValue("#sLname", TextBox2su.Text)
.Parameters.AddWithValue("#sNum", TextBox3num.Text)
End With
Try
SQLConnection.Open()
sqlCommand.ExecuteNonQuery()
iReturn = True
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
iReturn = False
Finally
SQLConnection.Close()
End Try
End Using
End Using
Return iReturn
End Function
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim iReturn As Boolean
Using SQLConnection As New MySqlConnection(connString)
Using sqlCommand As New MySqlCommand()
With sqlCommand
.CommandText = "UPDATE students SET StudentNumber = #sNumber, " & TextBox1sn.Text &
"`Name`= #sName, Surname=#sLname, Number= #sNum, " & _
"College= #sCollege, Course= " & _
("Where StudentNumber = #oldNumber")
.Connection = SQLConnection
.Parameters.AddWithValue("#sNumber", SqlDbType.VarChar).Value = TextBox1sn.Text
.Parameters.Add("#sName", MySqlDbType.VarChar).Value = TextBox1name.Text
.Parameters.Add("#sLname", MySqlDbType.VarChar).Value = TextBox2su.Text
.Parameters.Add("#sNum", MySqlDbType.VarChar).Value = TextBox3num.Text
.Parameters.AddWithValue("#oldNumber", SqlDbType.VarChar).Value = TextBox1sn.Text
End With
Try
SQLConnection.Open()
sqlCommand.ExecuteNonQuery()
iReturn = True
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
iReturn = False
Finally
SQLConnection.Close()
End Try
End Using
End Using
End Sub
End Class
The cause of your error is the AddWithValue called on the first 4 parameters. The AddWithValue second parameter is the value that you want to assign to the parameter, not its type.
Using the type as second parameter means that AddWithValue creates a parameter of type integer and when you assign the string to the Value property you get the exception
You should change everything to use the verbose, but more safe Add
With sqlCommand
.CommandText = "UPDATE students SET StudentNumber = #sNumber, " & _
"`Name`= #sName, Surname=#sLname, Number= #sNum, " & _
"College= #sCollege, Course= #sCourse, Year = #sYr " & _
"Where StudentNumber = #oldNumber")
.Connection = SQLConnection
.Parameters.Add("#sNumber", SqlDbType.VarChar).Value = TextBox1sn.Text
.Parameters.Add("#sName", MySqlDbType.VarChar).Value = TextBox1name.Text
.Parameters.Add("#sLname", MySqlDbType.VarChar).Value = TextBox2su.Text
.Parameters.Add("#sNum", MySqlDbType.VarChar).Value = TextBox3num.Text
.Parameters.Add("#sCollege", ???).Value = ComboBox1.SelectedItem
.Parameters.Add("#sCourse", ???).Value = ComboBox2.SelectedItem
.Parameters.Add("#sYr", ???).Value = ComboBox3.SelectedItem
.Parameters.Add("#oldNumber, SqlDbType.VarChar).Value = ???
Of course someone has already told you that you need to use parameter for every part of your query, (also the WHERE needs a parameter)
Also notice that I have changed the enum passed to the Add method to use the specific one for MySql. SqlDbType is the generic enum used for the base classes and I am not sure if it has the same values of the MySql one, better use the matching ones then.
Finally the last three parameters use the same approach but I don't know what is the intended MySqlDbType and if you need to convert the SelectedItem property of the combo to the appropriate datatype
EDIT
There is also the problem of Name being a reserved keyword, put it between backticks and it is not clear what are you trying to update. You use the Number in your WHERE condition. There is no need to update the Number on the same record with the value of the textbox used also for the search. Instead, if you are trying to change the Number field with a new value then you need to use the original value in the WHERE condition.

vb.net/mysql show more then 1 row in TextBox

I just started messing around with Visual basic (vb.net) and am trying to show more then 1 database row in a TextBox, so far I have this:
Private Sub foobox_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString = connStr
Try
conn.Open()
Catch myerror As MySqlException
MsgBox("No connection")
End Try
Dim myAdaptor As New MySqlDataAdapter
Dim sqlquery = "SELECT * FROM foo ORDER BY id DESC"
Dim myCommand As New MySqlCommand()
myCommand.Connection = conn
myCommand.CommandText = sqlquery
myAdaptor.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader()
If myData.HasRows Then
myData.Read()
Viewer.Text = myData("foo1") & myData("foo2")
End If
myData.Close()
conn.Close()
End Sub
which connects to a database successfully but but it only outputs 1 row, how can I get it to output more?
You need a loop reading data and storing line after line in a StringBuilder.
Then, when exiting from the reading loop set the Text property of your textbox
Dim sb as StringBuilder = new StringBuilder()
While myData.Read()
sb.AppendLine(myData("foo1") & myData("foo2"))
End While
Viewer.Text = sb.ToString
and, of course, your textbox should have the MultiLine property set to True
Apart from this direct answer to your question, your code should be changed to dispose the connection and the datareader after use, I have also removed the DataAdapter because is not needed here
Using conn = New MySqlConnection(connStr)
Try
conn.Open()
Catch myerror As MySqlException
MsgBox("No connection")
End Try
Dim sqlquery = "SELECT * FROM foo ORDER BY id DESC"
Dim myCommand As New SqlCommand(sqlquery, conn)
Using myData = myCommand.ExecuteReader()
Dim sb as StringBuilder = new StringBuilder()
While myData.Read()
sb.AppendLine(myData("foo1") & myData("foo2"))
End While
Viewer.Text = sb.ToString
End Using
End Using
You need some kind of loop. I would also use the Using statement to ensure that all unmanaged resources are disposed even in case of an exception(it also closes the connection):
Using conn As New MySqlConnection(connStr)
Using myCommand As New MySqlCommand("SELECT * FROM foo ORDER BY id DESC", conn)
Try
conn.Open()
Using myData = myCommand.ExecuteReader()
If myData.HasRows Then
While myData.Read()
Dim line = String.Format("{0}{1}{2}",
myData.GetString(myData.GetOrdinal("foo1")),
myData.GetString(myData.GetOrdinal("foo1")),
Environment.NewLine)
viewer.Text &= line
End While
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Using
End Using
However, if you want to show multiple records i would recommend a ListBox instead. It's more efficient with many items and it also separates them logical from each other.
( just replace viewer.Text &= line with ListBox1.Items.Add(line) )

data reader in vb.net

Please help, how do I make a while loop equivalent of this for loop. So that I could read from one row in the table of mysql database and display it on the combobox in vb.net.
I use this code, but its definitely not useful if there are 3 or more items that are added in the row:
Dim i As Integer
Dim rdr As Odbc.OdbcDataReader
rdr = con.readfrom_drug_type_table()
For i = 0 To 1
If rdr.HasRows = True Then
rdr.Read()
ComboBox2.Items.Add(rdr("Drug_type"))
End If
Next i
I want to read all the data from that the Drug_type row
Please help, thanks
If you want to read only first row than just use
If rdr.Read() Then
ComboBox2.Items.Add(rdr("Drug_type"))
End If
Update
Try
myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
'you need to provide password for sql server
myConnection.Open()
myCommand = New SqlCommand("Select * from discounts", myConnection)
dr = myCommand.ExecuteReader
While dr.Read()
WriteLine(dr(0))
WriteLine(dr(1))
WriteLine(dr(2))
WriteLine(dr(3))
WriteLine(dr(4))
' writing to console
End While
Catch
End Try
dr.Close()
myConnection.Close()
#pranay
You don't need the nested loops.
Try
myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
myConnection.Open()
myCommand = New SqlCommand("Select * from discounts", myConnection)
dr = myCommand.ExecuteReader()
While dr.Read()
WriteLine(dr(0))
WriteLine(dr(1))
WriteLine(dr(2))
WriteLine(dr(3))
WriteLine(dr(4))
End While
dr.Close()
Finally
myConnection.Close()
End Try