Hi I am trying to import data from a database into variable in my program but I keep on getting the error:
System.InvalidCastException: 'Conversion from type 'DBNull' to type 'String' is not valid.'
Dim value As Integer
Dim MySqlConn As MySqlConnection
Dim sql As New MySqlCommand
Dim dataAdapter As New MySqlDataAdapter
Dim dataFromDB As New DataSet
Dim numrows As Integer
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=localhost;user id=root;database=gamedata;"
Try
MySqlConn.Open()
sql = New MySqlCommand("SELECT Ccost FROM cards WHERE `UserName` = '" & UserName & "' AND `Game` = '" & game & "'", MySqlConn)
dataAdapter = New MySqlDataAdapter(sql)
dataAdapter.Fill(dataFromDB)
numrows = dataFromDB.Tables(0).Rows.Count
For counter = 1 To numrows - 1
value = dataFromDB.Tables(0).Rows(counter).Item(0)
Next
sql = New MySqlCommand("Select Level,Health,Score,PlayerTime FROM savedata WHERE `UserName` = '" & UserName & "' AND `Game` = '" & game & "'", MySqlConn)
dataAdapter = New MySqlDataAdapter(sql)
dataAdapter.Fill(dataFromDB)
numrows = dataFromDB.Tables(0).Rows.Count
'For counter = 0 To 1
level = dataFromDB.Tables(0).Rows(0).Item(0)
Phealth = dataFromDB.Tables(0).Rows(0).Item(1)
score = dataFromDB.Tables(0).Rows(0).Item(2)
time = dataFromDB.Tables(0).Rows(0).Item(3)
Catch ex As MySqlException
MsgBox("Error " & ex.Message)
End Try
database code:
use `Gamedata`;
create table `SaveData`
(`GameCode` int AUTO_INCREMENT not null,`Game` enum('1','2','3','4') not null,`UserName` varchar(20) not null,`level` int not null, `Health` int not null,`Score` int not null,`PlayerTime` time not null,
foreign key(`UserName`) REFERENCES `player` (`UserName`),
primary key(`GameCode`));
Here is a slightly different approach. This code requires the following Imports at the top of the file.
Imports System.Data.SqlTypes
You need to declare your database objects with Using blocks so they will be closed and disposed even if there is an error. Queries should always be written using parameters. Not it only does it avoid sql injection but it is easier to read and write.
A database integer can be null but not so in .net. The SqlInt32 has an .IsNull property that we can use for testing. If you try to convert a null string to a string by, for example calling .ToString, you will get an error.
Private ConStr As String = "server=localhost;user id=root;database=gamedata;"
Private Sub OpCode(UserName As String, Game As String)
Dim value As Integer
Dim dt As New DataTable
Dim strSql = "SELECT Ccost FROM cards WHERE `UserName` = #UserName AND `Game` = #Game"
Try
Using Sql As New MySqlCommand(strSql, New MySqlConnection(ConStr))
Sql.Connection.Open()
Sql.Parameters.Add("#UserName", MySqlDbType.VarChar).Value = UserName
Sql.Parameters.Add("#Game", MySqlDbType.VarChar).Value = Game
Dim obj = Sql.ExecuteScalar
value = If(obj Is Nothing, 0, CInt(obj))
Sql.CommandText = "Select Level,Health,Score,PlayerTime FROM savedata WHERE `UserName` = #UserName AND `Game` = #Game;"
Using reader = Sql.ExecuteReader
dt.Load(reader)
End Using
End Using
Dim level = If(CType(dt.Rows(0)(0), SqlString).IsNull, "", dt.Rows(0)(0).ToString)
Dim Phealth = If(CType(dt.Rows(0)(1), SqlString).IsNull, "", dt.Rows(0)(1).ToString)
Dim score = If(CType(dt.Rows(0)(2), SqlInt32).IsNull, 0, CInt(dt.Rows(0)(2)))
Dim time = If(CType(dt.Rows(0)(3), SqlInt32).IsNull, 0, CInt(dt.Rows(0)(3)))
Catch ex As MySqlException
MsgBox("Error " & ex.Message)
End Try
End Sub
Related
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.
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.
I'm working on my project which displays a list of employee. here, the information and picture of the employee will be shown. my project can now show the list of employees in the listbox and when I double click on an employee, his/her profile will be shown on a textbox. my problem is that i can't make their pictures to show in the picturebox. I already stored their picture on a table in my database along with their id, name, and profile. It only shows the picture of the first employee on the table. can anybody help me?
here's what I already done:
I populated the listbox:
Call Connect()
With Me
STRSQL = "Select employee_name from Employees"
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
reader = myCmd.ExecuteReader
If (reader.Read()) Then
reader.Close()
adptr.SelectCommand = myCmd
adptr.Fill(dt)
lstEmployee.DisplayMember = "employee_name"
lstEmployee.ValueMember = "employee_id"
If dt.Rows.Count > 0 Then
For i As Integer = 0 To dt.Rows.Count - 1
lstEmployee.Items.Add(dt.Rows(i)("employee_name"))
Next
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End With
here's how I show the info on textbox
Dim FileSize As UInt32
Dim mStream As New System.IO.MemoryStream()
Dim arrImage() As Byte = mStream.GetBuffer()
FileSize = mStream.Length
Dim cmd As New MySqlCommandBuilder
Call Connect()
With Me
STRSQL = "select employee_name, profile from Employees where employee_id = " & lstEmployee.SelectedIndex
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
reader = myCmd.ExecuteReader
If (reader.Read()) Then
txtName.Text = reader("employee_name")
txtProfile.Text = reader("profile")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
myConn.Close()
End Try
adptr.SelectCommand = myCmd
dt = New DataTable
adptr = New MySqlDataAdapter("select picture from Employees", myConn)
cmd = New MySqlCommandBuilder
adptr.Fill(dt)
Dim lb() As Byte = dt.Rows(0).Item("picture")
Dim lstr As New System.IO.MemoryStream(lb)
pix.Image = Image.FromStream(lstr)
pix.SizeMode = PictureBoxSizeMode.StretchImage
lstr.Close()
You miss the where clause is must be like to search a one employee to view there image.
adptr = _
New MySqlDataAdapter("select picture from Employees " + _
"where employee_id = " & lstEmployee.SelectedIndex, myConn)
cmd = New MySqlCommandBuilder
adptr.Fill(dt)
Dim lb() As Byte = dt.Rows(0).Item("picture")
Dim lstr As New System.IO.MemoryStream(lb)
pix.Image = Image.FromStream(lstr)
pix.SizeMode = PictureBoxSizeMode.StretchImage
lstr.Close()
P.S.: You must study the LINQ (Language-Integrated Query) for better approach.
Good day everyone. I am trying to create a program that will transfer all of the contents of a text file into a database. So far, my code works, but my code only inserts the first line of the text file into the database. What should I add to solve the problem? I am noob at programming sorry.
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim filename As String = "C:\Users\user\desktop\swipe.txt"
Dim Query As String
Dim data As String = System.IO.File.ReadAllText(filename)
Dim Loc, _date, time, temp, id As String
Loc = data.Substring(0, 3)
_date = data.Substring(3, 8)
time = data.Substring(11, 4)
temp = data.Substring(15, 3)
id = data.Substring(18, 3)
Query = "INSERT INTO tbl_entrance_swipe VALUES ('" + Loc + "','" + _date + "','" + time + "','" + temp + "','" + id + "')"
Dim con As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=cph;User ID=root;Password=;")
Try
con.Open()
Dim sql As MySqlCommand = New MySqlCommand(Query, con)
sql.ExecuteNonQuery()
MsgBox("Record is Successfully Inserted")
con.Close()
Catch ex As Exception
con.Close()
MsgBox("Record is not Inserted" + ex.Message)
End Try
End Sub
End Class
You are using File.ReadAllText which reads the complete text of the file. You want to read line by line, therefore you can use File.ReadLines(deferred executed) or File.ReadAllLines(reads all into a String()).
You should also use sql-parameters to prevent sql-injection and incorrect implicit type conversions or localization issues. Finally, use the Using statement to ensure that all unmanaged resources are disposed (f.e. the connection gets closed even on error):
Dim filename As String = "C:\Users\user\desktop\swipe.txt"
Dim allLines As String() = File.ReadAllLines(filename)
Dim query As String = "INSERT INTO tbl_entrance_swipe VALUES (#Loc, #Date, #Time, #Temp, #Id)"
Using con As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=cph;User ID=root;Password=;")
con.Open()
Using cmd As New MySql.Data.MySqlClient.MySqlCommand(query, con)
For Each line In allLines
Dim loc, dt, time, temp, id As String
loc = line.Substring(0, 3)
dt = line.Substring(3, 8)
time = line.Substring(11, 4)
temp = line.Substring(15, 3)
id = line.Substring(18, 3)
cmd.Parameters.Clear()
Dim pLoc As New MySql.Data.MySqlClient.MySqlParameter("#Loc", MySqlDbType.VarChar)
pLoc.Value = loc
cmd.Parameters.Add(pLoc)
Dim pDate As New MySql.Data.MySqlClient.MySqlParameter("#Date", MySqlDbType.VarChar)
pDate.Value = dt
cmd.Parameters.Add(pDate)
Dim pTime As New MySql.Data.MySqlClient.MySqlParameter("#Time", MySqlDbType.VarChar)
pTime.Value = time
cmd.Parameters.Add(pTime)
Dim pTemp As New MySql.Data.MySqlClient.MySqlParameter("#Temp", MySqlDbType.VarChar)
pTemp.Value = temp
cmd.Parameters.Add(pTemp)
Dim pId As New MySql.Data.MySqlClient.MySqlParameter("#Id", MySqlDbType.VarChar)
pId.Value = id
cmd.Parameters.Add(pId)
cmd.ExecuteNonQuery()
Next
MsgBox("All records were inserted successfully")
con.Close()
End Using
End Using
I have the following code where table name is student and column name is sem_of_study from the type of INT
Dim userquery As String = "select sem_of_study from student where username='" + Session("user") + "'"
Dim usercom As New SqlCommand(userquery, conn)
Dim a = usercom.ExecuteReader
I was wondering if I could convert the SQL Command into integer so I can use it in IF statements!!
so that variable a would
if a=1 then
else if a=2 then
Besides the fact you should use parameterized queries (search SO -- plenty of examples), you need to do something like this reading in the DataReader rows:
Dim a as Integer
Dim myReader As SqlDataReader = usercom.ExecuteReader()
If myReader.HasRows Then
myReader.Read()
a = myReader.GetInt32(0)
End If
And for the parameters:
Dim userquery As String = "select sem_of_study from student where username=#username"
Dim usercom as SqlCommand = new SqlCommand()
usercom.Connection = conn
usercom.CommandType = CommandType.Text
usercom.CommendText = userquery
usercom.Parameters.AddWithValue("username", Session("user"))