ExecuteScalar Error when Creating Custom ID - mysql

im currently facing problem with executeScalar when i create custom ID. the error is
InvalidOperationException was unhandled by user code.
Message=Connection must be valid and open.
Below is my code :
Dim str As String = "select isnull(max(idcr_record),0)+1 from cr_record where Emplid = '" & Session("Emplid") & "'"
Dim com As New MySqlCommand()
'this line was the error
'
Dim count As Integer = Convert.ToInt32(com.ExecuteScalar())
If count = 1 Then
'insert if no record found
'
Dim cc As New MySqlCommand("insert into cr_record values (" & count & "," & Session("Emplid") & ")")
cc.ExecuteNonQuery()
Else
'update becoz record already exist
'
Dim upd As String = "update cr_record set idcr_record = " & count & " where Emplid = " & Session("Emplid") & " "
Dim cc As New MySqlCommand(upd)
cc.ExecuteNonQuery()
End If
Dim length As Integer = 0
Dim val As String = Convert.ToString(count)
length = val.Length
If length = 1 Then
val = "CR " + "00000" & Convert.ToString(count)
End If
If length = 2 Then
val = "CR " + "0000" & Convert.ToString(count)
End If
If length = 3 Then
val = "CR " + "000" & Convert.ToString(count)
End If
If length = 4 Then
val = "CR " + "00" & Convert.ToString(count)
End If
If length = 5 Then
val = "CR " + "0" & Convert.ToString(count)
End If
cr_id = "" & val

At least, you need to pass your SQL command string and SqlConnection object to SqlCommand object before you can execute the command :
Dim str As String = "select isnull(max(idcr_record),0)+1 from cr_record where Emplid = '" & Session("Emplid") & "'"
Dim conn As New MySqlConnection
conn.ConnectionString = "....."
'pass your SQL command string and MySqlConnection object to MySqlCommand
'
Dim com As New MySqlCommand(str, conn)
conn.Open()
Dim count As Integer = Convert.ToInt32(com.ExecuteScalar())

Related

VB.net connect to database pop out 'Truncated incorrect DOUBLE value: 'System.Windows.Forms.TextBox, Text: 1''

I was using vb.net and try to update the row of the sourcedata in the gridview which connected to the database.I'm using primary key id in the database.
Below is the related code,This is to generate the primary key ID:
Private Sub GetId()
Dim Id As Integer
Dim query As String
Dim nameid As Integer
query = "select Id from information.information order by Id Desc"
sqlConn.ConnectionString = "server =" + server + ";" + "user id=" + username + ";" _
+ "password=" + password + ";" + "database = " + database
sqlConn.Open()
sqlCmd = New MySqlCommand(query, sqlConn)
sqlRd = sqlCmd.ExecuteReader()
If (sqlRd.Read()) Then
nameid = Integer.Parse(sqlRd(0)) + 1
Id = nameid.ToString("00")
ElseIf (Convert.IsDBNull(sqlRd)) Then
Id = ("01")
Else
Id = ("01")
End If
sqlConn.Close()
txtId.Text = Id
End Sub
This is to update the rows:
Private Sub Editrow()
sqlConn.ConnectionString = "server =" + server + ";" + "user id=" + username + ";" _
+ "password=" + password + ";" + "database = " + database
sqlConn.Open()
sqlCmd.Connection = sqlConn
With sqlCmd
.CommandText = "Update information.information set Name=#Name,EmailAddress=#EmailAddress,PhoneNumber=#PhoneNumber,DOB=#DOB,Address=#Address where Id=#newId"
.CommandType = CommandType.Text
.Parameters.AddWithValue("#newId", txtId)
.Parameters.AddWithValue("#Name", txtName)
.Parameters.AddWithValue("#EmailAddress", txtEmailAddress)
.Parameters.AddWithValue("#PhoneNumber", txtPhoneNumber)
.Parameters.AddWithValue("#DOB", txtDob)
.Parameters.AddWithValue("#Address", txtAddress)
End With
sqlCmd.ExecuteNonQuery()
sqlConn.Close()
updateTable()
'clear txtbox values
txtId.Text = ""
txtName.Text = ""
txtEmailAddress.Text = ""
txtPhoneNumber.Text = ""
txtDob.Text = ""
txtAddress.Text = ""
End Sub
this is to get the rows:
Private Sub Getrow()
Try
txtId.Text = DataGridView1.SelectedRows(0).Cells(0).Value.ToString()
txtName.Text = DataGridView1.SelectedRows(0).Cells(1).Value
txtEmailAddress.Text = DataGridView1.SelectedRows(0).Cells(2).Value
txtPhoneNumber.Text = DataGridView1.SelectedRows(0).Cells(3).Value
txtDob.Text = DataGridView1.SelectedRows(0).Cells(4).Value
txtAddress.Text = DataGridView1.SelectedRows(0).Cells(5).Value
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
And here is the error:
error message
here is my database setting:
database
I am making the following assumption: txtId, txtName, txtEmailAddress, etc. are textboxes on a form.
In your code you currently are passing the Textbox object. I think if you pass the Text property of your textbox (ie txtName.Text) instead it will fix your issue.
With sqlCmd
.CommandText = "Update information.information set Name=#Name,EmailAddress=#EmailAddress,PhoneNumber=#PhoneNumber,DOB=#DOB,Address=#Address where Id=#newId"
.CommandType = CommandType.Text
.Parameters.AddWithValue("#newId", txtId.Text)
.Parameters.AddWithValue("#Name", txtName.Text)
.Parameters.AddWithValue("#EmailAddress", txtEmailAddress.Text)
.Parameters.AddWithValue("#PhoneNumber", txtPhoneNumber.Text)
.Parameters.AddWithValue("#DOB", txtDob.Text)
.Parameters.AddWithValue("#Address", txtAddress.Text)
End With

How to get data from database mysql with For clause in Vb net

I have a code on vb.net, I want to use looping for vb.net to retrieve data from the mysql database.
the problem that I face seems to repeat loop not working properly, the data obtained only repeats the first data ..
can anyone help me ??
conn.Open()
sqlConn1 = "select * from transaksi"
data3 = New MySqlDataAdapter(sqlConn1, conn)
data3.Fill(ds3, "transaksi")
Dim keterangan As String
Dim c4 As String = String.Empty
For c As Integer = 0 To ds3.Tables("transaksi").Rows.Count - 1
sqlConn2 = "select * from transaksi"
data32 = New MySqlDataAdapter(sqlConn2, conn)
data32.Fill(ds32, "transaksi")
c4 = ds32.Tables("transaksi").Rows(c).Item("idTransaksi")
'For d As Integer = 0 To s - 1
Dim nilaihasil As Double
Dim nilaix As Double
Dim var_a As Double
Dim var_b As Double
For f As Integer = 0 To 5 - 1
sqlConn6 = "select * from transaksidetail WHERE idTransaksi = '" & c4 & "'"
data6 = New MySqlDataAdapter(sqlConn6, conn)
data6.Fill(ds6, "transaksidetail")
var_a = ds6.Tables("transaksidetail").Rows(f).Item("nilaiTransaksidetail")
sqlConn7 = "select nilai from cluster WHERE idKriteria = '" & ds6.Tables("transaksidetail").Rows(f).Item("idKriteria") & "' AND kode = 'C0'"
data7 = New MySqlDataAdapter(sqlConn7, conn)
data7.Fill(ds7, "cluster")
var_b = ds7.Tables("cluster").Rows(f).Item("nilai")
'MessageBox.Show(var_a & var_b)
nilaix += ((var_a ^ 2) - (var_b ^ 2))
Next
nilaihasil = Math.Sqrt(nilaix)
perintah.CommandType = CommandType.Text
perintah.CommandText = "INSERT INTO tempcluster (idTemp,idTransaksi,nilai,cluster) VALUES ('','" & c4 & "','" & nilaihasil & "','C0')"
perintah.Connection = conn
perintah.ExecuteNonQuery()
Next c
conn.Close()
I think your problem might be refilling the DataTable transaksi inside the loop. Comments and explanation in line.
Private Sub OPCode2()
Dim conn As New MySqlConnection("Your Connection String")
conn.Open()
Dim sqlConn1 = "select * from transaksi"
Dim data3 = New MySqlDataAdapter(sqlConn1, conn)
Dim ds3 As New DataSet
data3.Fill(ds3, "transaksi")
Dim keterangan As String = ""
Dim c4 As String = String.Empty
For c As Integer = 0 To ds3.Tables("transaksi").Rows.Count - 1
'It looks like you are doing the same thing twice
'Anyway, you don't want to do it over and over in the loop
'sqlConn2 = "select * from transaksi"
'data32 = New MySqlDataAdapter(sqlConn2, conn)
'data32.Fill(ds32, "transaksi")
c4 = ds3.Tables("transaksi").Rows(c).Item("idTransaksi").ToString
Dim nilaihasil As Double
Dim nilaix As Double
Dim var_a As Double
Dim var_b As Double
Dim sqlConn6 = "select * from transaksidetail WHERE idTransaksi = '" & c4 & "'"
Dim data6 = New MySqlDataAdapter(sqlConn6, conn)
Dim ds6 As New DataSet
data6.Fill(ds6, "transaksidetail")
'This looks a little silly, how about To 4
For f As Integer = 0 To 5 - 1
'Move the following out of the loop
'No sense doing the same thing 5 times
'sqlConn6 = "select * from transaksidetail WHERE idTransaksi = '" & c4 & "'"
'data6 = New MySqlDataAdapter(sqlConn6, conn)
'data6.Fill(ds6, "transaksidetail")
var_a = CDbl(ds6.Tables("transaksidetail").Rows(f).Item("nilaiTransaksidetail"))
Dim sqlConn7 = "select nilai from cluster WHERE idKriteria = '" & ds6.Tables("transaksidetail").Rows(f).Item("idKriteria").ToString & "' AND kode = 'C0'"
Dim data7 = New MySqlDataAdapter(sqlConn7, conn)
Dim ds7 As New DataSet
data7.Fill(ds7, "cluster")
var_b = CDbl(ds7.Tables("cluster").Rows(f).Item("nilai"))
'MessageBox.Show(var_a & var_b)
nilaix += ((var_a ^ 2) - (var_b ^ 2))
Next
nilaihasil = Math.Sqrt(nilaix)
Dim perintah As New MySqlCommand
perintah.CommandType = CommandType.Text
perintah.CommandText = "INSERT INTO tempcluster (idTemp,idTransaksi,nilai,cluster) VALUES ('','" & c4 & "','" & nilaihasil & "','C0')"
perintah.Connection = conn
perintah.ExecuteNonQuery()
Next c
conn.Close()
End Sub

Mysql Replace function issue

I want to update my table with replace function, but the result is not my expected result, how can I solve this problem?
Lets say I have a LONGTEXT columns(using_id) with value like this 1,2,3,4,5,6,7,8,9,10,11,
Now I want to remove '1,' so I write in this way:-
Dim query As String = "UPDATE curr_id SET using_id = REPLACE(using_id,'" & $"{g_currTicketID}," & "','')"
But the result become 2,3,4,5,6,7,8,9,10,1 How can I keep my '11,'?
Expected result: 2,3,4,5,6,7,8,9,10,11,
Public Sub TicketStatusUpdate(p_str As String)
'Login => GET NEXT ID > UPDATE USING ID > UPDATE NEXT ID
'Sales => RELEASE > UPDATE USED ID > GET NEXT ID > UPDATE USING ID > UPDATE NEXT ID
Select Case p_str
Case "UPDATE USED ID"
TicketStatusUpdate("RELEASE")
Dim query As String = "UPDATE curr_id SET used_id = CONCAT(used_id, '" & $"{g_currTicketID}," & "')"
Using cmd = New MySqlCommand(query, conn)
cmd.ExecuteNonQuery()
End Using
TicketStatusUpdate("GET NEXT ID")
Case "GET NEXT ID"
Dim query_select = "SELECT * FROM curr_id WHERE DATE(curr_date) = '" & Format(DateTime.Today.Date, "yyyy-MM-dd") & "' "
Dim reader As MySqlDataReader
Dim IsNewDay As Boolean = False
Using cmd = New MySqlCommand(query_select, conn)
reader = cmd.ExecuteReader
reader.Read()
If reader.HasRows Then
g_currTicketID = reader.GetInt32("next_id")
Else
g_currTicketID = 1
IsNewDay = True
End If
reader.Close()
End Using
If IsNewDay Then TicketStatusUpdate("RESET")
TicketStatusUpdate("UPDATE USING ID")
TicketStatusUpdate("UPDATE NEXT ID")
Case "UPDATE USING ID"
Dim query As String = "UPDATE curr_id SET using_id = CONCAT(using_id, '" & $"{g_currTicketID}," & "')"
Using cmd = New MySqlCommand(query, conn)
cmd.ExecuteNonQuery()
End Using
Case "UPDATE NEXT ID"
Dim query1 As String = "SELECT * FROM curr_id"
Dim str_usingID As String = ""
Dim str_usedID As String = ""
Dim reader As MySqlDataReader
Using cmd = New MySqlCommand(query1, conn)
reader = cmd.ExecuteReader
reader.Read()
str_usingID = reader.GetString("using_id").ToString
str_usedID = reader.GetString("used_id").ToString
reader.Close()
End Using
Dim str_allID As String = (str_usingID + str_usedID).TrimEnd(",")
Dim strArray As String() = str_allID.Split(",")
Dim intArray As Integer() = Array.ConvertAll(strArray, Function(s) Int32.Parse(s))
Array.Sort(Of Integer)(intArray)
Dim nextID As Integer = FirstMissing(intArray)
Dim query2 As String = "UPDATE curr_id SET next_id = '" & nextID & "'"
Using cmd = New MySqlCommand(query2, conn)
cmd.ExecuteNonQuery()
End Using
Case "RELEASE"
Dim query As String = "UPDATE curr_id SET using_id = REPLACE(using_id,'" & $"{g_currTicketID}," & "','')"
Using cmd = New MySqlCommand(query, conn)
cmd.ExecuteNonQuery()
End Using
Case "RESET"
Dim query As String = "UPDATE curr_id SET next_id='',used_id='',using_id=''"
Using cmd = New MySqlCommand(query, conn)
cmd.ExecuteNonQuery()
End Using
End Select
End Sub
Private Function FirstMissing(sequence() As Integer) As Integer
Dim seq = sequence
Dim firstMissingNumer = Int32.MinValue
For i = 1 To Math.Min(seq.Last, seq.Count)
If seq(i - 1) <> i Then
firstMissingNumer = i
Exit For
End If
Next
If firstMissingNumer = Int32.MinValue Then
Return seq.Max + 1
Else
Return firstMissingNumer
End If
End Function
When I logout the application it will call TicketStatusUpdate("RELEASE") to remove the g_currTicketID from using_id column.
Examples:
g_currTicketID = 1
using_id = 1,11,21,31,
When TicketStatusUpdate("RELEASE") called it will remove all '1,' from using_id, so the result will become 1,2,3 which is not the result that I want, I only want to remove '1,' and keep '11,21,31,'
Instead of replace just value, you could try to replace both value and boundary character
(in your case, comma ',' is a boundary character).
Example:
With g_currTicketID = 1, using_id = 1,11,21,31, then
replaceValue = CONCAT(',',g_currTicketID,',') = ',1,'
stringToReplace = CONCAT(',',using_id,',') = ',1,11,21,31,'
using_id = TRIM(BOTH ',' FROM REPLACE(stringToReplace, replaceValue, ','))
Your updat statement could be like this
Dim query As String = "UPDATE curr_id SET using_id = TRIM(BOTH ',' FROM REPLACE(CONCAT(',' ,using_id, ','), '," & $"{g_currTicketID}," & "', ','))"

parsing database columns and values to MySQL statement in module

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.

Mysql server version for the riGht syntax to use near '",2016-01-13','2016-01-14')' at line 1

Private Sub btnIssue_Click (sender As System.Object, e As Syste.EventArgs) Handles btnIssue_Click
Try
Dim dbquery As String = "insert into tblIssued
values (" & cmbBookId.SelectedText & ",' " &
cmbIssueto.SelectedText & " ',' " &
txtIssuedDate.Text & " ',' " &
datepickerduedate.Text & " ' ) "
Dim dbConnection As New MysqlConnection(dbconstring)
Dim dbCmd As New MySqlCommand(dbquery,dbCOnnection)
Dim dbReader As MySqlDataReader
dbConnection.Open()
dbReader = dbCmd.ExecuteReader()
MsgBox("Issued")
You need to provide the column name as well like
insert into tblIssued(col1,col2,col3,col4)
values(value1,value2,value3,value4)
So in your case it would be like
Dim query As String = "insert into tblIssued(Bookid,Idno,Issuedate,Duedate)
values (#Bookid,#Idno,#Issuedate,#Duedate)"
Dim command As New SqlCommand(query, conn)
command.Parameters.Add("#Bookid", SqlDbType.Int).Value = Convert.toInt32(cmbBookId.SelectedText)
command.Parameters.Add("#Idno", SqlDbType.Int).Value = Convert.toInt32(cmbIssueto.Text)
command.Parameters.Add("#Issuedate", SqlDbType.DateTime).Value = txtIssuedDate.Text
command.Parameters.Add("#Duedate", SqlDbType.DateTime).Value = datepickerduedate.Text