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()
Related
I'm trying to count records on my saved datas.
Here is my code:
Dim pl_qry As String
Dim pl_cmd As New Odbc.OdbcCommand
Dim pl_dr As Odbc.OdbcDataReader
If txtPurpose.Text = "PERSONAL LOAN" Then
pl_qry = "select count(purpose) from details where borrower_id = '" & bor_id & "' and purpose = '" & "PERSONAL LOAN" & "'"
pl_cmd.CommandText = pl_qry
pl_cmd.Connection = con
pl_dr = pl_cmd.ExecuteScalar
pl_dr.Read()
If Not pl_dr.IsDBNull(0) Then
MsgBox(pl_dr.GetString(0))
End If
End If
I got my error in this line
pl_dr = pl_cmd.ExecuteScalar
If you have check the ExecuteScalar method, you will notice it will return the first column of the first row of your SQL.
Problem is you have assigned the result to 'OdbcDataReader`
Dim pl_dr As Odbc.OdbcDataReader
but maybe you can just get the result directly:
Int64 result = Convert.ToInt64(cmd.ExecuteScalar())
I'm trying to create a dynamic MySQL INSERT INTO...WHERE NOT EXIST statement by parsing the table name, array of columns, array of values and conditional column and value to a subroutine in a separate module but i keep hitting the Column count doesn't match value count at row 1 error. Below is the code:
Sub InsertRecord(ByVal tbl As String, ByVal cols() As String, ByVal params() As String, _
ByVal colCondition As String, ByVal paramCondition As String) 'As String
'Create new string of columns
Dim myCols As String = ""
For Each col As String In cols
myCols &= col & ", "
Next
Dim newCols As String = myCols.Remove(myCols.Count - 2, 2)
MsgBox(newCols)
Dim scols As String = newCols.Insert(0, "`").Replace(", ", "`, `") & "`"
MsgBox(scols)
'Create new string of parameters
Dim myParams As String = ""
For Each param In params
myParams &= param & ", "
Next
Dim newParams As String = myParams.Remove(myParams.Count - 2, 2)
MsgBox(newParams)
Dim sparams As String = newParams.Insert(0, "'").Replace(", ", "', '") & "'"
MsgBox(sparams)
'End
Dim p As String = paramCondition.Insert(0, "'") & "'"
'Try
'Dim insRemarks As String = "done"
con = New MySqlConnection("Server=localhost; Database=etms; Uid=root; Pwd=;")
comA = New MySqlCommand
'INSERT NEW RECORD.
'THIS GIVES THE ERROR
comA.CommandText = "INSERT INTO " & tbl & " (" & scols & ") SELECT * FROM (SELECT #params) AS tmp "
comA.CommandText &= "WHERE NOT EXISTS (SELECT " & colCondition & " FROM " & tbl & " WHERE " & colCondition & " = #param) limit 1"
comA.Parameters.AddWithValue("#param", p)
comA.Parameters.AddWithValue("#params", sparams)
'THIS STATIC CODE WORKS FINE.
'comA.CommandText = "INSERT INTO state (`st_state`, `ctry_Id`) SELECT * FROM (SELECT 'a', '1') AS tmp "
'comA.CommandText &= "WHERE NOT EXISTS (SELECT st_state FROM state WHERE st_state = 'a') limit 1"
comA.Connection = con
con.Open()
comA.ExecuteNonQuery()
con.Close()
'Release used up components
comA.Parameters.Clear()
comA.Dispose()
comA = Nothing
con = Nothing
MsgBox("done.")
'Return insRemarks
'Catch ex As Exception
'MsgBox(ex.Message.ToString & vbCrLf & vbCrLf & comA.CommandText.ToString)
'Return "Error"
'End Try
End Sub
As seen, i tried a lot of permutations (introducing inverted quotation marks) to no avail.
I'll be glad if someone could help out.
I've tried many different methods to join the following from;
StockCode Finished_Goods_Codes
100137 2105109
100137 2105110
100137 2105111
To;
StockCode Finished_Goods_Codes
100137 2105109, 2105110, 2105111
My Current Code is as follows;
Public Function ListQuery()
Dim curr As Database
Dim rs As Recordset
Dim SQLCmd As String
Dim productList As String
Set curr = CurrentDb()
SQLCmd = "SELECT Finished_Goods_Codes FROM TEMP_codes WHERE [StockCode] = """ & StockCode & """"
Set rs = curr.OpenRecordset(SQLCmd)
If Not rs.EOF Then
rs.MoveFirst
End If
Do While Not rs.EOF
productList = productList & rs(0) & ", "
rs.MoveNext
Loop
ListQuery = productList
End Function
My Query currently runs the following;
SELECT TEMP_codes.StockCode, ListQuery([Products]) AS [List of Products]
FROM TEMP_codes
GROUP BY TEMP_codes.StockCode;
Could you please help as i'm really stuck on this.
Many Thanks in advance.
Based on the answer given for the question Microsoft Access condense multiple lines in a table, here are the steps:
1 Create the following function
Public Function GetList(SQL As String _
, Optional ColumnDelimeter As String = ", " _
, Optional RowDelimeter As String = vbCrLf) As String
'PURPOSE: to return a combined string from the passed query
'ARGS:
' 1. SQL is a valid Select statement
' 2. ColumnDelimiter is the character(s) that separate each column
' 3. RowDelimiter is the character(s) that separate each row
'RETURN VAL: Concatenated list
'DESIGN NOTES:
'EXAMPLE CALL: =GetList("Select Col1,Col2 From Table1 Where Table1.Key = " & OuterTable.Key)
Const PROCNAME = "GetList"
Const adClipString = 2
Dim oConn As ADODB.Connection
Dim oRS As ADODB.Recordset
Dim sResult As String
On Error GoTo ProcErr
Set oConn = CurrentProject.Connection
Set oRS = oConn.Execute(SQL)
sResult = oRS.GetString(adClipString, -1, ColumnDelimeter, RowDelimeter)
If Right(sResult, Len(RowDelimeter)) = RowDelimeter Then
sResult = Mid$(sResult, 1, Len(sResult) - Len(RowDelimeter))
End If
GetList = sResult
oRS.Close
oConn.Close
CleanUp:
Set oRS = Nothing
Set oConn = Nothing
Exit Function
ProcErr:
' insert error handler
Resume CleanUp
End Function
2 Add a Reference for the function in the Module (Tools -> References). Add the Reference Micorosft ActiveX Data Objects 6.1 Library (or the most recent one available).
3 Save the Module with a name different from the function name, say Concatenation
4 Run the following query
SELECT T.StockCode, GetList("Select Finished_Goods_Codes From TEMP_codes As T1 Where T1.StockCode = " & [T].[StockCode],"",", ") AS Finished_Goods_Codes
FROM TEMP_codes AS T
GROUP BY T.StockCode;
I'm trying to put to array my SQL query string but I encounter this error
An unhandled exception of type 'System.NullReferenceException' occurred
What is the possible problem I have?
Dim myList As ArrayList
Dim cnt As Integer
cnt = lvTrans.SelectedItems.Count
For values As Integer = 0 To cnt
Dim vals1 = lvTrans.FocusedItem.SubItems(9).Text()
sqlString2 = " UNION " & _
"SELECT * FROM tbltransmital_mkk t INNER JOIN tbltransmital1_mkk t1 ON t.transmital_no = t1.transmital_no WHERE t.transmital_no='" & txtTrans.Text & _
"' AND t1.autokey ='" & vals1 & "'"
myList.Add(sqlString2)
Next
sqlString = sqlString1 & sqlString2
MsgBox(sqlString)
myList is Nothing. You never create an instance (with New).
As there's no reason to use an ArrayList at all (except you're somehow forced to work with .Net 1.1 or something), better use a List(Of String) instead, e.g.:
Dim myList = New List(Of String) ' <-- create an instance with "New"
i hope you can help me. Fist of all, sorry if my English is annoying, i'm not a native speaker.
I'm getting this error and i can't see what i'm doing wrong. I have a program that fills a local MySQL DB with data from another program that uses an OLEB DB.
So it compares the tables and upload new data on demand. But i'm getting this error with only one table using the same Sub that i used with other tables.
Unknown column 'lpedidos.serie' in 'field list'
The problem is that 'lpedidos.serie' exists indeed. So here is the code of the sub, please don't laugh, i know that maybe is extremely inefficient, but i'm just a noob.
Public Sub notIndexedTables(table As DataTable, table2 As DataTable, tableNA As String)
Dim temptable As DataTable
temptable = table.Clone
Dim tablename As String = temptable.TableName
Dim myAdapter As MySql.Data.MySqlClient.MySqlDataAdapter
Dim SQL As String
Dim newconn As New MySql.Data.MySqlClient.MySqlConnection
newconn = mysqlConnection()
newconn.Open()
SQL = "TRUNCATE " & tableNA
myAdapter = New MySql.Data.MySqlClient.MySqlDataAdapter()
Dim command As MySql.Data.MySqlClient.MySqlCommand
command = New MySql.Data.MySqlClient.MySqlCommand(SQL, newconn)
myAdapter.DeleteCommand = command
myAdapter.DeleteCommand.ExecuteNonQuery()
For Each row As DataRow In table.Rows()
Dim columnNumber As Int32 = row.ItemArray.Count
Dim i As Integer = 0
Dim s1 As String = "("
For Each columna In row.ItemArray
i = i + 1
If i = columnNumber Then
s1 = s1 + CStr(table2.Columns.Item(i - 1).ColumnName) & ")"
Else
s1 = s1 & CStr(table2.Columns.Item(i - 1).ColumnName) & ", "
End If
Next
Dim s2 As String = "("
i = 0
For i = 0 To (columnNumber - 2)
s2 = s2 & "'" & CStr(row.Item(i)) & "', "
Next
s2 = s2 & "'" & CStr(row.Item(columnNumber - 1)) & "')"
SQL = "INSERT INTO " & tableNA & " " & s1 & " VALUES " & s2
myAdapter = New MySql.Data.MySqlClient.MySqlDataAdapter()
' myCommand = New MySql.Data.MySqlClient.MySqlCommandBuilder(myAdapter)
command = New MySql.Data.MySqlClient.MySqlCommand(SQL, newconn)
myAdapter.InsertCommand = command
myAdapter.InsertCommand.ExecuteNonQuery()
Next
newconn.Close()
newconn.Dispose()
End Sub
Basically it takes the MySQL table (tableNA), truncates it (this procedure is for tables with no index, there is other procedure for tables with unique index) and fills it with the data from the OLEB table (table) and takes the column names from the temporal copy of the MySQL table (table2) (maybe there is no need to use the table2 in this case... but anyway).
Here is the exception and the value that SQL string takes when the exception is thrown.
And here is a screenshot of the table structure in phpMyAdmin.
When you declare the New MySqlConnection you need to put the connection string in there and specify the database name. Can you show your connection string?
Dim myConnection As New MySqlConnection(myConnString)
myConnection.Open()
If that doesn't solve the problem, then try another column name and make sure it isn't a reserved keyword.