Why does MysqlCommand.ExecuteScalar return System.NullReferenceException - mysql

I am using MySQL in a VB 2013 project. I am trying to get the number of records in a table running
Dim SQLstr As String = "SELECT COUNT(*) FROM lieferantenartikel WHERE LiefID=1 AND LfAIDLief=1"
Dim CheckExist As New MySqlCommand(SQLstr, New MySqlConnection(strConn))
Try
Dim recEx As Integer = CheckExist.ExecuteScalar()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
By definition COUNT(*) is supposed to return a scalar number, i.e. 0 if no records exist or otherwise any other positive number.
But I am getting a System.NullReferenceException. What am I doing wrong?

I had similar issues. This happened when a table had no entries. You can Do a workaround with "ISNULL". But maybe there is a better way.

In fact the problem has gon when I used an open connection instead of the connection object ! Thank you, plutonix. I have obviously overseen in the documentation that the connection has to be open.
So the corrent code is now:
Dim SQLstr As String = "SELECT COUNT(*) FROM lieferantenartikel WHERE LiefID=1 AND LfAIDLief=1"
Dim cConn as New MySqlConnection(strConn)
cConn.Open()
Dim CheckExist As New MySqlCommand(SQLstr, cConn)
Try
Dim recEx As Integer = CheckExist.ExecuteScalar()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Thank you very much for your quick help!e

Related

Input string was not in a correct format message error during update record vb.net and mysql

I have MySQL Database and VB.Net project.
I have created a sub to execute any SQL statement and it's working well.
Public Sub Me_Sub_GetUpdate(ByVal SqlStr As String, ByVal xPar() As MySqlParameter)
Try
xCMD = New MySqlCommand(SqlStr, Conn)
xCMD.CommandType = CommandType.Text
If xPar IsNot Nothing Then
For i As Integer = 0 To xPar.Length - 1
xCMD.Parameters.Add(xPar(i))
Next
End If
If Conn.State = ConnectionState.Open Then Conn.Close()
Conn.Open()
xCMD.ExecuteNonQuery()
Conn.Close()
xCMD.Dispose()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
when I use the next subroutine to update a record:
Try
Dim SqlStr As String
Dim xParam As MySqlParameter() = New MySqlParameter(1) {}
xParam(0) = New MySqlParameter("#ID", SqlDbType.TinyInt)
xParam(0).Value = 1
xParam(1) = New MySqlParameter("#TheName1", SqlDbType.NVarChar)
xParam(1).Value = Trim(Me.t1.Text)
SqlStr = "UPDATE tblcominfo Set TheName1=#TheName1 Where ID = #ID"
xCLS.Me_Sub_GetUpdate(SqlStr, xParam)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
I got a message (Input string was not in a correct format)!!
When I deleted the parameters and run the update code with direct values it's working!!
I don't know what's the problem, can you help me?
The problem is that you're using SqlDbType, not MySqlDbType. SqlDbType is used by the SQL Server provider. Since you're using MySQL, you need to use MySqlDbType.
The constructor you're calling is not the one you expected:
new MySqlParameter("#TheName1", SqlDbType.NVarChar)
...is calling the constructor that takes (name As String, value As Object) because there's no overload that takes SqlDbType. You're then overwriting the value, and the MySqlDbType property is whatever the default is (probably MySqlDbType.Decimal).
On the other hand, if you pass a MySqlDbType value:
new MySqlParameter("#TheName1", MySqlDbType.VarChar)
...it will call the constructor that takes (name As String, dbType As MySqlDbType) and the MySqlDbType property will be initialized from it.

Redefining/Re-setting parameters in MySQL query

I have the following code for inserting data into a table using a MySQL query in VB.NET
Dim MySqlCmdStr = "INSERT INTO tb_idlink(id1,id2) " &
"VALUES (#par1,#par2)"
MySqlCmd.CommandText = MySqlCmdStr
Dim checkedItem As Object
For Each checkedItem In CheckedListBox_1.CheckedItems
Try
MySqlCmd.Connection = MySqlConn
With MySqlCmd
.Parameters.AddWithValue("#par1", currentID)
.Parameters.AddWithValue("#par2", checkedItem.ToString())
End With
MySqlConn.Open()
MySqlCmd.ExecuteNonQuery()
MySqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
Next
My problem is if I have more than one box checked in CheckedListBox_1 then on the second loop an exception that says something like "parameter #par1 already defined". Is there a way I can re-define it? I'm not entirely familiar with the whole API.
Also, I'm not 100% sure if looping it is the best way to do this, but it's the first thing that popped into my head. Feel free to suggest an alternative way of doing this.
You dont redefine the parameters, you just supply a new value:
Dim SQL = "INSERT INTO tb_idlink (id1,id2) VALUES (#par1,#par2)"
Using dbcon As New MySqlConnection(MySQLConnStr)
Using cmd As New MySqlCommand(SQL, dbcon)
' define the parameter names and types
cmd.Parameters.Add("#par1", MySqlDbType.Int32)
cmd.Parameters.Add("#par2", MySqlDbType.Int32) ' ????
dbcon.Open()
For Each checkedItem In CheckedListBox1.CheckedItems
' provide the parameter values
cmd.Parameters("#par1").Value = currentID
cmd.Parameters("#par2").Value = Convert.ToInt32(checkedItem)
cmd.ExecuteNonQuery()
Next
End Using
End Using
Your code appears to reuse a global connection, that is ill-advised. The above uses Using blocks to create, use and and dispose of the DbConnection and DbCommand objects in the smallest scope possible
You should favor Add rather than AddWithValue so you can specify the datatype rather than forcing the the DB Provider guess and reduce the chance of data type mismatch errors.
These datatypes are a guess; CurrentId is not defined anywhere and given the names, both seem to be integers not strings.

MySqlDataReader not returning data

As part of a project to import data into wordpress via screen scraping I've a database table of old and new URL's stored in a MySQL database. In the example below the ExecuteReader command doesn't appear to be returning any data (-1 rows effected), I've ran the SQL via workbench and that returns data, so it's not the SQL or data in the database.
At other times within the code I've called ExecuteNonQuery() and ExecuteScalar() both without issue (so it isn't the connection string).
Any ideas what to try next?
Dim SQL As String
Dim conn As MySqlConnection = New MySqlConnection(_CONNECTIONSTRING)
SQL = "SELECT OrgURL, NewURL FROM `wp_user`.`tbl_linkdata`"
Try
conn.Open()
Dim cmd As MySqlCommand = New MySqlCommand(SQL, conn)
Dim dr As MySqlDataReader = cmd.ExecuteReader()
While (dr.Read)
LinkHashMap.Add(dr.GetString(0), dr.GetString(1))
End While
Console.ForegroundColor = ConsoleColor.Cyan
Console.WriteLine("The Hash map contains " + dr.RecordsAffected + " rows")
dr.Close()
Catch ex As Exception
Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine("Exception loading the hashtable : " + ex.Message)
Finally
conn.Dispose()
End Try
DataReader.RecordsAffected always returns -1 for a SELECT command. What does LinkHashMap.Count return? In MySqlDataReader it is the same:
"The number of rows changed, inserted, or deleted. -1 for SELECT
statements"
If you want to count the number of records you can use LinkHashMap.Count.
You: "LinkHashMap is "Nothing" "
How do you want to add something to it without initializing it first? A NullReferenceException should have happened. So initialize the dictionary (or whatever it is) first via constructor:
Dim LinkHashMap As New Dictionary(Of String, String)
While (dr.Read)
LinkHashMap.Add(dr.GetString(0), dr.GetString(1))
End While

VB.net data retrieval and display

So, for some reason I can't work out I think the below is only retrieving the 1st letter of the value within the column I'm trying to search. (Note: the database is called m1 and contains 11 columns in total).
I tested the query first in SQL Admin and it worked properly (I think).
I then wrote this myself using documentation, I think I've more that likely made a mistake somewhere..
Dim hostnameQuery As String = "SELECT `HOSTNAME` FROM `m1` WHERE 1"
Dim SQLConnection As New MySqlConnection(My.Settings.connStr)
Dim cmd As New MySqlCommand(hostnameQuery, SQLConnection)
Try
SQLConnection.Open()
cmd.ExecuteNonQuery()
Dim reader As MySqlDataReader
reader = cmd.ExecuteReader
While reader.Read
main.Label64.Text = (reader.GetChar(0))
End While
Catch ex As Exception
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
I added this to a button click so when I click the button only the letter 'M' appears but the value is 'M1'
What have I done wrong?
That's because you requested only a character. Try using GetString() instead of GetChar() :
main.Label64.Text = (reader.GetString(0))
There are many things that can be improved in your code.
First of all, you can remove the condition WHERE 1, because it means "EVERYTHING" so it is not useful.
Secondly, you can avoid calling cmd.ExecuteNonQuery() because it is usually used to run an instruction that does not return anything (like INSERT).
Finally, if you are interested only to the first returned row, you can avoid the While loop and use cmd.ExecuteScalar() instead.
To summarize, instead of:
cmd.ExecuteNonQuery()
Dim reader As MySqlDataReader
reader = cmd.ExecuteReader
While reader.Read
main.Label64.Text = (reader.GetChar(0))
End While
simply do this:
main.Label64.Text = Convert.ToString(cmd.ExecuteScalar())

Get first entry from MySQL database in VB

Could you please help me? I just want to take the first row of a table in a mysql database via Visual Basic. I prefer simple code. The only thing i found is using a while, thing that i dont want. Thanks in advance!
Try something like this
Try
Dim sql As String = "SELECT first_row FROM test_table WHERE id = 1"
Dim cmd as OleDbCommand
cmd = New OleDbCommand(sql, Reconnect)
Dim itmReader as SqlDataReader
itmReader = cmd.ExecuteReader
If itmReader.Read Then
Dim firstRowData as String
firstRowData = itmReader.Item("first_row")
MessageBox.Show(firstRowData)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try