Please I badly needed your help. I have the following code that returns a table from ms access displayed in a data grid view based on the user's input. But when I tried to run it, I have encountered the error "Syntax error (comma) in query expression 'lastname = '' , firstname = '' , midname = '''." Please someone help me
here is my code.
Dim sql As String = "SELECT `lastname` as 'FAMILY NAME',`firstname` as 'NAME', `midname` AS 'MIDDLE NAME', `sex` as 'SEX', `birthdate` as 'BIRTHDAY', `Address` as 'ADDRESS', `barangay` AS 'BARANGAY', `patientID` AS 'PID' FROM `tblinformation_offline` WHERE lastname = '" & TextBox1.Text & "' , firstname = '" & TextBox3.Text & "' , midname = '" & TextBox4.Text & "' "
Dim cn As New OleDbConnection(constring)
cn.Open()
Dim da As New OleDbDataAdapter(sql, cn)
Dim ds As New DataSet
da.Fill(ds, "AccessData")
cn.Close()
With Me.DataGridView1
.DataSource = ds
.DataMember = "AccessData"
End With
ds = Nothing
da.Dispose()
cn = Nothing
First problem, a WHERE clause is a one or more conditions linked together by a logical operator like AND or OR. Your WHERE list a series of values and this is not a valid syntax
.... FROM `tblinformation_offline`
WHERE lastname = 'xxxxx'
AND firstname = 'yyyyyy'
AND midname = 'zzzzz"
This will fix your immediate error.
As you can see I have removed the string concatenation to let you see more clearly your errors, but now there is the problem of your use of string concatenation to build sql queries. Don't do it but use a parameterized query
In a parameterized query you use the Parameters collection of the MySqlCommand to pass your values, while the string that contains the text is filled with parameter's placeholders
Dim sql As String = "SELECT ...... FROM `tblinformation_offline` " & _
"WHERE lastname = #lname AND firstname = #fname AND midname = #mname"
Using cn As New OleDbConnection(constring)
Using da As New OleDbDataAdapter(sql, cn)
da.SelectCommand.Parameters.Add("#lname", MySqlDbType.VarChar).Value = TextBox1.Text
da.SelectCommand.Parameters.Add("#fname", MySqlDbType.VarChar).Value = TextBox3.Text
da.SelectCommand.Parameters.Add("#mname", MySqlDbType.VarChar).Value = TextBox4.Text
Dim ds As New DataSet
da.Fill(ds, "AccessData")
cn.Close()
With Me.DataGridView1
.DataSource = ds
.DataMember = "AccessData"
End With
ds = Nothing
End Using
End Using
Finally in the query text used there are errors. When you write
"SELECT `lastname` as 'FAMILY NAME' ....
You are creating records where the value of the column lastname is filled with the string "FAMILY NAME" because you use the single quote character instead of the backticks as you do around the columns (the same applies to the other columns as well)
Related
SQL = "UPDATE `tblitems` SET `itemsOnHand` = `itemsOnHand` - '" & PartnumItemsNumericUpDown.Value & "' WHERE `itemID` = '" & itemIDTextBoxX.Text & "' ;"
SQL = "UPDATE `tblitems` SET `itemsOnHand` = `itemsOnHand` + '" & PartnumItemsNumericUpDown.Value & "' WHERE `itemID` = '" & itemIDTextBoxX.Text & "' ;"
--- Just want to ask why the first sub function sql command (-) works but (+) wont...please help. itemsOnHand is integer type.
Please DO NOT concatenate strings to build sql command text. ALWAYS use Parameters it avoid sql injection. Parameter values are not executable code but a simple concatenation can hold "Delete * From tblitems."
I had to guess at the datatypes for the parameters.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ItemId As Integer
If Not Integer.TryParse(itemIDTextBoxX.Text, ItemId) Then
MessageBox.Show("Please enter a number in Item Id.")
Return
End If
Dim Sql = "UPDATE `tblitems` SET `itemsOnHand` = `itemsOnHand` - #PartNumber WHERE `itemID` = #ItemID"
Using con As New MySqlConnection(ConStr),
cmd As New MySqlCommand(Sql, con)
cmd.Parameters.Add("#PartNumber", MySqlDbType.Int32).Value = PartnumItemsNumericUpDown.Value
cmd.Parameters.Add("#ItemID", MySqlDbType.Int32).Value = ItemID
con.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
You are much less likely to run into problems with + and - using parameters since you don't need all the single quotes and double quotes.
The minus sign was interpreted as an arithmetic operator and the plus sign was interpreted as a concatenation character.
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
I was trying to Generate a unique ID by concatenating the User company + auto-generated ID
My output for my alphanumeric is "SNC001" but when I tried to generate the next ID I got the following error:
Conversion from string "SNC001" to type 'Integer' is not valid.
PS: the "SNC" came from this frm_Main_Menu.lblCompany.Text
Dim maxid As Object
Dim strid As String
Dim intid As Integer
Dim cmdid As New MySqlCommand
cmdid.Connection = cnn_MYSQL
cmdid.CommandText = "SELECT MAX(printed_id) as maxid FROM imports"
maxid = cmdid.ExecuteScalar
If maxid Is DBNull.Value Then
intid = "001"
Else
strid = CType(maxid, String)
intid = CType(strid, String)
intid = intid + 1
End If
Dim autoid As String = frm_Main_Menu.lblCompany.Text & intid.ToString().PadLeft(3, "001")
Dim cmd66 As New MySqlCommand
cmd66.Connection = cnn_MYSQL
cmd66.CommandText = "UPDATE imports " & _
" SET printed='" & "Y" & "', printed_id='" & autoid & "'" & _
" WHERE TIN = '" & id_selected &"'"
cmd66.ExecuteNonQuery()
You're assigning entire ID segment which has String type to Integer field/variable on this line, which is totally wrong and causing InvalidCastException:
intid = CType(strid, String) ' throws conversion error
The correct way is chopping off the prefix using Substring() starting from numeric part (i.e. 4th element which has index of 3) and convert the remainder to integer with either Convert.ToInt32() or Integer.Parse() method:
' using Convert.ToInt32
intid = Convert.ToInt32(strid.Substring(3, 3))
' alternative with Integer.Parse
intid = Integer.Parse(strid.Substring(3, 3))
Side note:
Better to use parameterized query instead of string concatenation to build the query, see following example below:
cmd66.CommandText = "UPDATE imports SET printed = 'Y', printed_id = #autoid WHERE TIN = #id_selected"
cmd66.Parameters.Add("#autoid", MySqlDbType.VarChar).Value = autoid
cmd66.Parameters.Add("#id_selected", MySqlDbType.Int).Value = id_selected
cmd66.ExecuteNonQuery()
I was trying to make a program in VB that accepts user information then saves it in MS access. I already connected MS access and Visual Basic ... The Code Works but it does not add the values inputted by the user in the MS access Table..
Public Sub AddNewStudent()
Dim firstname, middlename As String
con.Open()
Dim myconnect As New SqlClient.SqlConnection
myconnect.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\user.mdf;Integrated Security=True;user Instance=True"
Dim mycommand As SqlClient.SqlCommand = New SqlClient.SqlCommand()
mycommand.Connection = myconnect
mycommand.CommandText = "INSERT INTO Students(FirstName, MiddleName, LastName, Address, Cellphone Number, Course)" & _
"VALUES(" & Me.firstnameTB.Text & ",'" & Me.midnameTB.Text & "')"
firstname = firstnameTB.Text
middlename = midnameTB.Text
Try
mycommand.Parameters.AddWithValue("#firstname", SqlDbType.NVarChar).Value = Me.firstnameTB.Text()
mycommand.Parameters.Add("#middlename", SqlDbType.NVarChar).Value = Me.midnameTB.Text
mycommand.Parameters.Add("#lastnameTB", SqlDbType.NVarChar).Value = Me.lastnameTB.Text
mycommand.Parameters.Add("#addressTB", SqlDbType.NVarChar).Value = Me.addressTB.Text
mycommand.Parameters.Add("#cpnumTB", SqlDbType.NVarChar).Value = Me.cpnumTB.Text
mycommand.Parameters.Add("#courseCB", SqlDbType.NVarChar).Value = Me.courseCB.Text
MsgBox("Successfully added new student")
Catch ex As Exception
MsgBox(ex.Message)
End Try
myconnect.Close()
Firstly, you specify that six columns are to be inserted into but you then only provide two values. Secondly, you add parameters to your command but there are no parameters in your SQL code. You need to provide the same number of values as columns and those values need to be parameters. There are also a couple of other issues, like a column name with a space in it and calling AddWithValue improperly.
Public Sub AddNewStudent()
Dim firstname, middlename As String
con.Open()
Dim myconnect As New SqlClient.SqlConnection
myconnect.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\user.mdf;Integrated Security=True;user Instance=True"
Dim mycommand As SqlClient.SqlCommand = New SqlClient.SqlCommand()
mycommand.Connection = myconnect
mycommand.CommandText = "INSERT INTO Students(FirstName, MiddleName, LastName, Address, [Cellphone Number], Course)" & _
"VALUES(#firstname, middlename, #lastnameTB, #addressTB, #cpnumTB, #courseCB)"
firstname = firstnameTB.Text
middlename = midnameTB.Text
Try
mycommand.Parameters.Add("#firstname", SqlDbType.NVarChar).Value = Me.firstnameTB.Text
mycommand.Parameters.Add("#middlename", SqlDbType.NVarChar).Value = Me.midnameTB.Text
mycommand.Parameters.Add("#lastnameTB", SqlDbType.NVarChar).Value = Me.lastnameTB.Text
mycommand.Parameters.Add("#addressTB", SqlDbType.NVarChar).Value = Me.addressTB.Text
mycommand.Parameters.Add("#cpnumTB", SqlDbType.NVarChar).Value = Me.cpnumTB.Text
mycommand.Parameters.Add("#courseCB", SqlDbType.NVarChar).Value = Me.courseCB.Text
mycommand.ExecuteNonQuery
MsgBox("Successfully added new student")
Catch ex As Exception
MsgBox(ex.Message)
End Try
myconnect.Close()
change the command text like this
mycommand.CommandText = "INSERT INTO Students(FirstName, MiddleName, LastName, Address, [Cellphone Number], Course)" & _
"VALUES(#firstname, #middlename, #lastnameTB, #addressTB, #cpnumTB, #courseCB)"
change all of your lines setting data like this (its more convenient )
mycommand.Parameters.AddWithValue("#courseCB", courseCB.Text)
and finally write this code before
MsgBox("Successfully added new student")
mycommand.ExecuteNonQuery
I have been having a difficult time trying to figure this out. I wrote a SQL query to select certain data that has a relationship to a particular institution. Now the SQL query works perfectly fine as I tested it in MySQL Workbench, however, when I try to export that data from VB.NET onto a word document, it literally prints out the SQL.
Below is my code:
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim sqlTable As New DataTable
Dim sqlFundText As String = "select mutual_Fund_name, concat(contact_first_name,' ',contact_last_name) from mutual_fund mf, contact c, mutual_fund_has_contact mfhc, institution i, institution_has_mutual_Fund ihmf where mf.mutual_fund_id = mfhc.mutual_fund_id and c.contact_id = mfhc.contact_id and ihmf.mutual_fund_id = mf.mutual_fund_id and i.institution_id = ihmf.institution_id and i.institution_name ='" & InstitutionNameTextBox.Text & "' order by mutual_fund_name;"
With sqlCommand
.CommandText = sqlFundText
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(sqlTable)
End With
oPara9 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\endofdoc").Range)
With oPara9
.Range.Font.Bold = False
.Range.Text = sqlFundText
.Range.Font.Size = 10
.Format.SpaceAfter = 5
.Range.InsertParagraphAfter()
End With
And the result is:
As you can see it prints out the SQL statement.
I know it has to do with the
.Range.Text = sqlFundText
I just do not know how to fix it. Can anyone direct me the right way in fixing this?
The data from your query is in sqlTable. You'll need to extract the data from the data table and add that to your document instead of sqlFundText.
After your With sqlAdapter ... End With block you'll need to do something like:
Dim fundName as String
Dim contactName as String
For Each row in sqlTable.Rows
fundName = row[0].ToString()
contactName = row[1].ToString()
' Do something to put fundName and contactName into the document
Next
Here is a Sub() that accepts SQL and returns CSV. It isn't bullet proof but it works for my utility code.
In your case you could use tab as delimiter so that once the data is present in Word it can easily be converted to a table manually.
Yu could also use the code to create/populate a table in Word.
Function CSVReportFromSQL(SQL As String, Optional ToFilePath As String = "") As String
' note return differences if ToFilePath is provided
' If ToFilePath: check for 'OK' on return
' Else check return length = 0 for error
Try
Dim sOut As String = ""
Using con As New SqlConnection(g.OISConnectString)
Dim command As New SqlCommand(SQL, con)
con.Open()
' column headers
Dim rdr As SqlDataReader = command.ExecuteReader(CommandBehavior.SchemaOnly)
For i As Integer = 0 To rdr.FieldCount - 1
sOut &= "," & rdr.GetName(i)
Next
sOut = sOut.Substring(1) & vbCrLf
rdr.Close()
rdr = command.ExecuteReader()
While rdr.Read()
For i As Integer = 0 To rdr.FieldCount - 1
'Debug.Print(rdr.GetFieldType(i).Name & " " & rdr.GetName(i))
'http://msdn.microsoft.com/en-us/library/4e5xt97a(v=vs.80).aspx
Select Case rdr.GetFieldType(i).Name
Case "String", "DateTime"
sOut &= """" & rdr(i).ToString.Replace("""", """""") & ""","
Case Else
sOut &= rdr(i).ToString & ","
End Select
Next
sOut &= vbCrLf
End While
rdr.Close()
End Using
If ToFilePath.Length > 0 Then
My.Computer.FileSystem.WriteAllText(ToFilePath, sOut, False)
Return "OK"
Else
Return sOut
End If
Catch ex As Exception
If ToFilePath.Length > 0 Then
Return ex.Message
Else
MsgBox("Problem creating CSV Report" & vbCrLf & ex.Message)
Return ""
End If
End Try
End Function