I want to remove the rows of data gridview after use a query sql from database
i use this code
Try
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US")
Dim strConn As String
strConn = "DRIVER=PostgreSQL ANSI;SERVER=127.0.0.1;PORT=5432;UID=postgres;Password=azerty79;DATABASE=" & ComboBox2.Text & ";pwd=postgres;ReadOnly=0"
'strConn = "DRIVER={PostgreSQL ANSI};UID=postgres;pwd=postgres;LowerCaseIdentifier=0;UseServerSidePrepare=0;ByteaAsLongVarBinary=0;"
'strConn = "dsn=test;uid=postgres;pwd=postgres"
Dim cnDb As OdbcConnection
Dim dsDB As New DataSet
Dim adDb As OdbcDataAdapter
Dim cbDb As OdbcCommandBuilder
Dim cmd As OdbcCommand
Dim cmd1 As OdbcCommand
Dim adDb1 As OdbcDataAdapter
Dim dsDB1 As New DataSet
Dim dt As New DataTable
Dim pic As New PictureBox
cnDb = New OdbcConnection(strConn)
cnDb.Open()
dsDB = New DataSet
adDb = New OdbcDataAdapter
cbDb = New OdbcCommandBuilder(adDb)
'cmd.Parameters.Add("#id", OdbcType.NVarChar, "1")
For i = 1 To 3
' Create the SelectCommand.
cmd = New OdbcCommand("select b.id_detail_polygon,b.mappe_3,b.type_d_affaire,b.consistance,b.nbr_borne ,num_bornes,a.x,a.y,b.superficie_cs from point a right join (select (dp).path[1] d1,(dp).path[2] d2,(dp).geom d3 from (select st_dumppoints(geom) dp from polygon where id_detail_polygon ='" & i & "')a)dptable on st_equals(a.geom,dptable.d3),polygon b where id_detail_polygon='" & i & "'", cnDb) ' & _
'"WHERE id = ? ", cnDb)
cmd1 = New OdbcCommand("SELECT num_bornes,x,y FROM point RIGHT JOIN (SELECT (dp).path[1] As ringID,(dp).path[2] As pointID,(dp).geom ptgeom FROM (SELECT st_dumppoints(geom) dp FROM polygon WHERE id_detail_polygon='" & i & "' ) a) dptable ON ST_Equals(point.geom, dptable.ptgeom) ORDER BY dptable.pointID;", cnDb)
'cmd.Parameters.Add("#id", OdbcType.NVarChar, "1")
adDb = New OdbcDataAdapter(cmd)
adDb1 = New OdbcDataAdapter(cmd1)
adDb.Fill(dsDB, ComboBox1.Text)
adDb1.Fill(dsDB1, ComboBox1.Text)
DataGridView2.DataSource = dsDB
DataGridView3.DataSource = dsDB1
DataGridView2.DataMember = ComboBox1.Text
DataGridView3.DataMember = ComboBox1.Text
DataGridView2.DataSource = dsDB.DefaultViewManager
DataGridView3.DataSource = dsDB1.DefaultViewManager
Dim StrExport As String = ""
For Each R As DataGridViewRow In DataGridView3.Rows
For Each C As DataGridViewCell In R.Cells
If Not C.Value Is Nothing Then
StrExport &= C.Value.ToString & " "
Else
End If
Next
StrExport = StrExport.Substring(0, StrExport.Length - 1)
StrExport &= Environment.NewLine
Next
Dim fName As String = ""
SaveFileDialog1.InitialDirectory = "C:\Users\pc\Desktop\"
SaveFileDialog1.Filter = "dat files (*.dat)|*.dat"
SaveFileDialog1.FilterIndex = 2
SaveFileDialog1.Title = "dat"
SaveFileDialog1.RestoreDirectory = True
If (SaveFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
fName = SaveFileDialog1.FileName
End If
For j = 0 To 0
For x = 0 To DataGridView2.RowCount - 1
Dim tw As IO.TextWriter = New IO.StreamWriter(fName)
tw.Write(DataGridView2.Rows(j).Cells(0).Value & vbCr & vbLf & DataGridView2.Rows(j).Cells(1).Value & vbCr & vbLf & DataGridView2.Rows(j).Cells(2).Value & vbCr & vbLf & DataGridView2.Rows(j).Cells(3).Value & vbCr & vbLf & DataGridView2.Rows(j).Cells(4).Value & vbCr & vbLf & StrExport & " " & DataGridView2.Rows(j).Cells(8).Value)
tw.Close()
Next
Next
For Each row As DataGridViewRow In DataGridView2.Rows
DataGridView2.Rows.Remove(row)
Next
Next
Catch ex As Exception
MsgBox("ERROR :" + ex.Message)
End Try
MsgBox("Exported", vbInformation, "Successful")
But i get this problem below
Edit
Basing on your comment, I understand you don't want the data gone from the database bug instead from the grid. I would advise against using a dataset as you have done. A DataSet has a collection of DataTable objects that you can manipulate. I also see that you are removing every row in a For Each loop. You can remove these rows from the table or call the clear method on that table and you grid should reflect it. I have left the original answer to explain why this was happening. Edit
Without being able to tell what the error is, I'll just tell you that you cannot programmatically remove a row from a DataGridView if the DataSource is not an IBindingList with change event notification. OdbcDataAdapter does not implement IBindingList anywhere in its inheritance chain.
If you are not willing to change what you bind to, you can re-run the query to get the items and bind the grid again.
Related
I'm using vb.net to create API (MySQL). I know how to run create API for insert, select, and update. Now, I want to create an API that before data insert, must check the data, either exist in the table or not. If exist, then cannot insert the data. Below is my current vb.net code:
<WebMethod()>
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=False, XmlSerializeString:=False)>
Public Sub TGWL_insertLoadingSV(bl_id As String, cont_size_id As String, straping As String)
Dim mySQLConnection As MySqlConnection = New MySqlConnection("Data Source=" & l_DB_SERVER & ";Initial Catalog=" & l_DB_NAME & ";User Id=" & l_DB_USER & ";Password=" & l_DB_PASS)
Dim myDataAdapter As MySqlDataAdapter
Dim myDataset As DataSet = New DataSet
Dim myJson As String = ""
Try
If bl_id.Length > 0 Or cont_size_id.Length > 0 Or straping.Length > 0 Then
Dim myResponse As New failResponceClass
myDataAdapter = New MySqlDataAdapter
myDataAdapter.InsertCommand = New MySqlCommand("BEGIN;
INSERT INTO wla_loading_sv (bl_id, cont_size_id)
VALUES ('" & bl_id & "', '" & cont_size_id & "');
INSERT INTO wla_special_req (bl_id, straping)
VALUES('" & bl_id & "', '" & straping & "');
COMMIT;")
myDataAdapter.InsertCommand.Connection = mySQLConnection
mySQLConnection.Open()
myDataAdapter.InsertCommand.ExecuteNonQuery()
mySQLConnection.Close()
myResponse.statusCode = 1
myResponse.errCode = ""
myResponse.title = l_Title_TGWLAppUser
myResponse.desc = "TGWL App User"
Me.Context.Response.ContentType = "application/json; charset=utf-8"
Me.Context.Response.Write(JsonConvert.SerializeObject(myResponse))
Else
Dim myFailedResponce As New failResponceClass
myFailedResponce.statusCode = 0
myFailedResponce.errCode = "R01"
myFailedResponce.title = l_Title_TGWLAppUser
myFailedResponce.desc = "Missing parmeter."
Me.Context.Response.ContentType = "application/json; charset=utf-8"
Me.Context.Response.Write(JsonConvert.SerializeObject(myFailedResponce))
End If
Catch ex As SoapException
Throw ex
Finally
MySqlConnection.ClearPool(mySQLConnection)
MySqlConnection.ClearAllPools()
mySQLConnection.Close()
mySQLConnection.Dispose()
End Try
End Sub
Thus, how do I want to make sure that the bl_id does not exist at wla_loading_sv table? I want to make it in one API. Can someone help?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Good Day, to make things clear I will introduce my ongoing system which is "Gate attendance for student in our university", this system is consists of RFID reader RC522 and Arduino, the student should tap his/her RFID tag and the data retrieved shown at the monitor.. The system is our capstone project and it is done but the panel required us for another problem to be solved.
All functions is already done about the scanning,retrieving data,registering students , this will apply to the college students which is feel free to go out and in anytime depends on the schedule unlike highschool just one IN and OUT.
The two RFID reader is placed in Entrance and Exit of the University theres a system for out in the exit and In for the entrance.The data retrieved from in and out would save into the same table.
How can I show the messagebox warning to the students if he taps IN without go OUT first? I know it something about the query. but I have no Idea. I need some help here for my Capstone.. Any Comments and suggestion is appreciated advance.. Here is my code about the retrieving the data based on the RFID tag number shown in the textbox changed event..by the way my table studlogs is the one handled the attendance.
Private Sub studtag_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles studtag.TextChanged
Notenrolled.Close()
greet.Text = ""
PictureBox4.Visible = False
If studtag.Text = "44F2F38B" Then
Endday()
End If
If studtag.Text = recents.Text Then
Alreadylogin.Show()
ElseIf studtag.TextLength = 8 Then
DataGridView1.Sort(DataGridView1.Columns(6), System.ComponentModel.ListSortDirection.Descending)
con = New MySqlConnection
con.ConnectionString = "server=localhost;userid=root;password=1234;database=dat"
Dim query As String
query = "select * from dat.students"
cmd = New MySqlCommand(query, con)
Dim table As New DataTable
Try
con.Open()
'Gets or sets an SQL statement or stored procedure used to select records in the database.
With cmd
.Connection = con
.CommandText = "SELECT * from students where `studtags`='" & studtag.Text & "';"
End With
da.SelectCommand = cmd
da.Fill(table)
'it gets the data from specific column and fill it into Label
idno.Text = table.Rows(0).Item(1)
lastxt.Text = table.Rows(0).Item(2)
firstxt.Text = table.Rows(0).Item(3)
middletxt.Text = table.Rows(0).Item(4)
dob.Text = table.Rows(0).Item(6)
year.Text = table.Rows(0).Item(7)
crsetxt.Text = table.Rows(0).Item(10)
tagtxt.Text = studtag.Text
timein.Text = times.Text
dr = cmd.ExecuteReader()
dr.Read()
If dob.Text = bday.Text Then
greet.Text = firstxt.Text + " Today is your Birthday. Greetings :D."
PictureBox4.Visible = True
End If
Dim img() As Byte = CType(dr("studpic"), Byte())
Using ms As New IO.MemoryStream(img)
PictureBox1.Image = Image.FromStream(ms)
End Using
My.Computer.Audio.Play("C:\Users\BOR\Desktop\Parsu Gate\Parsu\audio\scanned.wav")
insert()
loadtable()
studdailyhistory()
Catch ex As Exception
Notenrolled.Show()
DataGridView1.Sort(DataGridView1.Columns(5), System.ComponentModel.ListSortDirection.Descending)
If studtag.Text = "44F2F38B" Then
Notenrolled.Close()
End If
Finally
con.Dispose()
con.Close()
End Try
End If
recents.Text = tagtxt.Text
End Sub
Public Sub insert()
con = New MySqlConnection
con.ConnectionString = "server=localhost;userid=root;password=1234;database=dat"
Dim reader As MySqlDataReader
Dim mstream As New System.IO.MemoryStream()
Dim arrImage() As Byte = mstream.GetBuffer()
mstream.Close()
Try
con.Open()
Dim query3 As String
query3 = "insert into dat.studlogs (studtags,idno,lastxt,firstxt,middletxt,dob,log,timein,crse,studpic) values ('" & tagtxt.Text & "','" & idno.Text & "','" & lastxt.Text & "','" & firstxt.Text & "','" & middletxt.Text & "','" & dob.Text & "','" & log.Text & "','" & timein.Text & "','" & crsetxt.Text & "',#studpic)"
cmd = New MySqlCommand(query3, con)
cmd.Parameters.AddWithValue("#studpic", arrImage)
reader = cmd.ExecuteReader
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
End Sub
Public Sub studdailyhistory()
con = New MySqlConnection
con.ConnectionString = "server=localhost;userid=root;password=1234;database=dat"
Dim reader As MySqlDataReader
Dim mstream As New System.IO.MemoryStream()
Dim arrImage() As Byte = mstream.GetBuffer()
mstream.Close()
Try
con.Open()
Dim query3 As String
query3 = "insert into dat.studdailyhistory (studtags,idno,lastxt,firstxt,middletxt,dob,log,timein,crse,dates,studpic) values ('" & tagtxt.Text & "','" & idno.Text & "','" & lastxt.Text & "','" & firstxt.Text & "','" & middletxt.Text & "','" & dob.Text & "','" & log.Text & "','" & timein.Text & "','" & crsetxt.Text & "','" & wholedate.Text & "',#studpic)"
cmd = New MySqlCommand(query3, con)
cmd.Parameters.AddWithValue("#studpic", arrImage)
reader = cmd.ExecuteReader
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
End Sub
Public Sub loadtable()
con = New MySqlConnection
con.ConnectionString = "server=localhost;userid=root;password=1234;database=dat"
Dim SDA As New MySqlDataAdapter
Dim dbDataset As New DataTable
Dim bSource As New BindingSource
Try
con.Open()
Dim query3 As String
query3 = "select idno as 'Student_ID',lastxt as 'LastName',firstxt as 'FirstName',middletxt as 'MiddleName',log as 'Status',timein as 'Timein',crse as 'Course' from dat.studlogs"
cmd = New MySqlCommand(query3, con)
SDA.SelectCommand = cmd
SDA.Fill(dbDataset)
bSource.DataSource = dbDataset
DataGridView1.DataSource = bSource
SDA.Update(dbDataset)
DataGridView1.Sort(DataGridView1.Columns(5), System.ComponentModel.ListSortDirection.Descending)
If dbDataset.Rows.Count > 0 Then
logins.Text = dbDataset.Rows.Count.ToString()
End If
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
End Sub
I am not sure i understand properly, but i guess u dont want the student be able to clock in twice without clock out.
You have multiple options.
The simpliest, you can use a status field in your db. When student clock in then save "status"=1 (student onsite), and at clockout "status"=0 (student not onsite). At every clock in and clock out you check the status of student. If 1 then can't clock in again as she/he onsite already.
Or you save in the log when they tap the fob it was an entrance or leave and when you query the table with student you order the table by last insert time so the last record will come up where you see the last status of the log.
Edit:
Add an extra bool type column in your database to students table like "studOnsite" and set the default value 0. When a student scan a card and you get the student details from the table here :
.CommandText = "SELECT * from students where `studtags`='" & studtag.Text & "';"
You will get back the "studOnsite" column aswell. After you can simply check the value like :
if (table.Rows(0).Item("studOnsite") then
'student already onsite so she/he is leaving
greet.Text = firstxt.Text & "Good bye!"
'update the student table and change "studOnsite" to false
'dim query as string=string.format("UPDATE students SET studOnsite=false WHERE studtags='{0}'",studtag.Text)
else
'student wasn't onsite so she/he is just arrived
greet.Text = firstxt.Text & "Welcome back!"
'update the student table and change "studOnsite" to true as student is onsite now
'dim query as string=string.format("UPDATE students SET studOnsite=true WHERE studtags='{0}'",studtag.Text)
end if
i have tried this code here to insert and show picture from database to picturebox : stackoverflow.com/questions/5624760/store-picture-to-database-retrieve-from-db-into-picturebox
and yeah, it is working , but when i tried to do update using the same syntax as insert it got this error :
this is the insert syntax i use :
Dim FileSize As UInt32
Dim mstream As New System.IO.MemoryStream()
gambar.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim arrImage() As Byte = mstream.GetBuffer()
FileSize = mstream.Length
mstream.Close()
call konek
strSQL = "insert into tbmahasiswa VALUES ('" & _
txtNIM.Text & "','" & _
txtNama.Text & "','" & _
Format(dtpTanggal.Value, "yyyy-MM-dd") & "','" & _
txtAlamat.Text & "','" & _
cboJurusan.Text & "',#gambar)"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
.Parameters.AddWithValue("#gambar", arrImage)
.ExecuteNonQuery()
End With
and this the code i use to show picture from database to picture box :
Dim imgData As Byte()
call konek
strSQL = "select * from tbMahasiswa where NIM ='" & txtNIM.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
Using rd = com.ExecuteReader
rd.Read()
If rd.HasRows Then
txtNama.Text = rd.Item(1)
dtpTanggal.Value = rd.Item(2)
txtAlamat.Text = rd.Item(3)
imgData = TryCast(rd.Item(5), Byte())
If imgData IsNot Nothing Then
Using ms As New MemoryStream(imgData)
gambar.Image = CType(Image.FromStream(ms), Image)
End Using
End If
End If
End Using
Both Insert and Retrieving Picture Code above is Working ! , and then i use this code for update :
Dim FileSize As UInt32
Dim mstream As New System.IO.MemoryStream()
gambar.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim arrImage() As Byte = mstream.GetBuffer()
FileSize = mstream.Length
mstream.Close()
call konek
strSQL = "update tbmahasiswa set Nama ='" & txtNama.Text & _
"', TglLahir ='" & Format(dtpTanggal.Value, "yyyy-MM-dd") & _
"', Alamat ='" & txtAlamat.Text & _
"', Jurusan ='" & cboJurusan.Text & _
"', gambar =' #gambar" & _
"' where NIM ='" & txtNIM.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
.Parameters.AddWithValue("#gambar", arrImage)
.ExecuteNonQuery()
End With
and then i got the error like in the picture above, all other data is correctly saved except the picture, it become some unknown file blob 8 KB size.
i'm still newbie at insert , update, delete picture in VB, please can you tell me what is wrong with the Update syntax code , is it already true but i'm missing something ? or is it totally wrong with the syntax ? please i need your guide here...
UPDATE :
actually there is "call konek" above "STRSQL" in the code, "konek" have the code for open the mysql connection,i put it in the separate module, here the full code in my module :
Module modKoneksi
Public conn As New MySql.Data.MySqlClient.MySqlConnection
Public rd As MySql.Data.MySqlClient.MySqlDataReader
Public com As MySql.Data.MySqlClient.MySqlCommand
Public strSQL As String
Public Sub konek()
conn.Close()
strSQL = "server='localhost';user='root';pwd='';database='dbsekolah';"
Try
conn.ConnectionString = strSQL
conn.Open()
Catch ex As MySql.Data.MySqlClient.MySqlException
MsgBox(ex.Message)
End
End Try
End Sub
End Module
hope this makes you easier to solve my problem
I know its late but this is the working code for me :
For retrieving the record from database with pictures :
Call konek() 'Call the connection module'
strSQL = "select * from tbMahasiswa where ID ='" & txtID.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
Using rd = com.ExecuteReader
rd.Read()
If rd.HasRows Then
txtNIM.Text = rd.Item(1)
txtNama.Text = rd.Item(2)
dtpTanggal.Value = rd.Item(3)
txtAlamat.Text = rd.Item(4)
imgData = TryCast(rd.Item(6), Byte())
If imgData IsNot Nothing Then
Using ms As New MemoryStream(imgData)
gambar.Image = CType(Image.FromStream(ms), Image)
End Using
End If
cboJurusan.SelectedIndex = cboJurusan.FindStringExact(rd.Item(5))
End If
End Using
For inserting record to database with pictures :
Call konek()
strSQL = "Insert Into tbmahasiswa Values ('" & txtID.Text & _
"','" & txtNIM.Text & _
"','" & txtNama.Text & _
"','" & Format(dtpTanggal.Value, "yyyy-MM-dd") & _
"','" & txtAlamat.Text & _
"','" & cboJurusan.Text & _
"',#gambar)"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
If opdGambar.FileName = Nothing Then 'opdGambar is a PictureBox name'
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = IO.File.ReadAllBytes("man-icon.png") 'Insert field gambar using an existing file in debug folder if file does not exist in PictureBox'
Else
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = IO.File.ReadAllBytes(opdGambar.FileName) 'Insert field gambar using an existing file in PictureBox'
End If
com.ExecuteNonQuery()
End With
For updating record to database with pictures :
Call konek()
Dim adapter As New MySql.Data.MySqlClient.MySqlDataAdapter("select gambar from tbmahasiswa where ID='" & txtID.Text & "'", conn)
Dim dt As New DataTable("gambar")
adapter.Fill(dt)
strSQL = "update tbmahasiswa set NIM='" & txtNIM.Text & _
"',Nama='" & txtNama.Text & _
"',TglLahir='" & Format(dtpTanggal.Value, "yyyy-MM-dd") & _
"',Alamat='" & txtAlamat.Text & _
"',Jurusan='" & cboJurusan.Text & _
"' ,Gambar=#gambar where id='" & txtID.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
If opdGambar.FileName = Nothing Then
Dim row As DataRow = dt.Rows(0)
Using ms As New IO.MemoryStream(CType(row(0), Byte()))
Dim img As Image = Image.FromStream(ms)
gambar.Image = img
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = (CType(row(0), Byte())) 'field gambar will use the current existing file in database if PictureBox does not have a file'
End Using
Else
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = IO.File.ReadAllBytes(opdGambar.FileName)
End If
com.ExecuteNonQuery()
End With
i hope for those who find the other answer a little confusing (like me), will find this answer helpful.
I am trying to make a POS (Point of Sales) Application and I got this error. "There is already an open DataReader associated with this Connection which must be closed first."
Below are my codes:
Database using MySQL
If txt_notr.Text = "" Or txt_kodep.Text = "" Or txt_item.Text = "" Or txt_gt.Text = "" Or txt_bayar.Text = "" Then
MsgBox("Data belum lengkap...!!!")
Exit Sub
Else
'Simpan ke tabel penjualan
db.Close()
db.Open()
Call Koneksi()
Dim simpan1 As String = "Insert Into tb_penjualan values('" & txt_notr.Text & "','" & Format(Now, "yyyy-MM-dd") & "','" & txt_kodep.Text & "','" & txt_item.Text & "','" & txt_gt.Text & "','" & txt_bayar.Text & "')"
cmd = New MySqlCommand(simpan1, db)
cmd.ExecuteNonQuery()
db.Close()
db.Open()
'Simpan ke tabel detail penjualan
For baris As Integer = 0 To DGV.Rows.Count - 2
Dim simpandet As String = "Insert into tb_detjual values('" & txt_notr.Text & "','" & DGV.Rows(baris).Cells(0).Value & "','" & DGV.Rows(baris).Cells(3).Value & "','" & DGV.Rows(baris).Cells(4).Value & "','" & DGV.Rows(baris).Cells(5).Value & "')"
cmd = New MySqlCommand(simpandet, db)
cmd.ExecuteNonQuery()
db.Close()
db.Open()
cmd = New MySqlCommand("Select * from tb_stok where id_obat = '" & DGV.Rows(baris).Cells(0).Value & "'", db)
dr = cmd.ExecuteReader
dr.Read()
If dr.HasRows Then
Dim kurangstok As String = "Update tb_stok set stok = '" & dr.Item("stok") - DGV.Rows(baris).Cells(4).Value & "' where id_obat = '" & DGV.Rows(baris).Cells(0).Value & "'"
cmd = New MySqlCommand(kurangstok, db)
cmd.ExecuteNonQuery() 'The Error shows here...
End If
Next
Call hapustemp()
Call bersih()
Call notrans()
End If
db.Close()
It's counter-intuitive, but ADO.Net providers use a feature called Connection Pooling, such that you really are better off creating a new connection object in most cases for individual calls to a database, rather than trying to keep a single database connection in your class to re-use. The code below shows the correct way to re-use the connection object: create a new connection for the method, and use it for the duration of the method. But then let the connection be collected when the method completes.
I noticed that you also have some seriously insecure code. Before doing any more work with databases, you should read up on Sql Injection. This is a HUGE issue. You should not be writing database code professionally if you don't know about it, and the correct way to avoid the problem.
Finally, the code uses some conventions that originated with older VBScript/VB6 and are no longer appropriate.
The code below solves all of those issues, and should be much faster by avoiding the need to run a SELECT from the database for each gridview row:
If String.IsNullOrWhiteSpace(txt_notr.Text) OrElse String.IsNullOrWhiteSpace(txt_kodep.Text) OrElse String.IsNullOrWhiteSpace(txt_item.Text) OrElse String.IsNullOrWhiteSpace(txt_gt.Text) OrElse String.IsNullOrWhiteSpace(txt_bayar.Text_ Then
MsgBox("Data belum lengkap...!!!")
Exit Sub
End If
'No need for an "Else". The "Exit Sub" takes care of it.
'Simpan ke tabel penjualan
'Note that I was able to let the database set the time stamp
Dim sql As String = "Insert Into tb_penjualan values(#notr, current_timestamp, #kodep, #item, #gt, #bayar);"
'The "Using" keyword will guarantee the connection closes, even if an exception is thrown
Using cn As New MySqlConnection(" connection string here "), _
cmd As New MySqlCommand(sql, cn)
'Use parameter placeholders rather than string concatenation. This avoids a SERIOUS security issue.
' I have to guess parameter types/lengths, but you should use actual types/lengths that match your database
cmd.Parameters.Add("#notr", MySqlDbType.Int32).Value = CInt(txt_notr.Text)
cmd.Parameters.Add("#kodep", MySqlDbType.VarChar, 20).Value = txt_kodep.Text
cmd.Parameters.Add("#item", MySqlDbType.VarString, 1000).Value = txt_item.Text
cmd.Parameters.Add("#gt", MySqlDbType.VarChar, 50).Value = txt_gt.Text
cmd.Parameters.Add("#bayar", MySqlDbType.VarChar, 50).Value = txt_bayar.Text
cn.Open()
cmd.ExecuteNonQuery()
'Two sql statements in a single call to the database.
'This is MUCH better than the Insert/Select/Update process you were using
sql = "INSERT INTO tb_detjual VALUES (#notr, #c0, #c3, #c4, #c5);" & _
"UPDATE tb_stok SET stok = stok - #c4 WHERE id_obat = #c0;"
'See how I was able to re-use the same parameters in the query.
cmd.Parameters.Clear()
cmd.CommandText = sql
cmd.Parameters.Add("#notr", MySqlDbType.Int32).Value = CInt(txt_notr.Text)
cmd.Parameters.Add("#c0", MySqlDbType.VarChar, 50)
cmd.Parameters.Add("#c3", MySqlDbType.VarChar, 50)
cmd.Parameters.Add("#c4", MySqlDbType.VarChar, 50)
cmd.Parameters.Add("#c5", MySqlDbType.VarChar, 50)
'Simpan ke tabel detail penjualan
For baris As Integer = 0 To DGV.Rows.Count - 2
'I'm able to re-use the same parameters for each loop
cmd.Parameters("#c0").Value = DGV.Rows(baris).Cells(0).Value
cmd.Parameters("#c3").Value = DGV.Rows(baris).Cells(3).Value
cmd.Parameters("#c4").Value = DGV.Rows(baris).Cells(4).Value
cmd.Parameters("#c5").Value = DGV.Rows(baris).Cells(5).Value
cmd.ExecuteNonQuery()
Next
End Using
hapustemp()
bersih()
notrans()
When I run this function
For RepeatBooking = 1 To 51
dateConvertedDateToBook = dateDateToBook.Date
dateDateToBook = dateDateToBook.AddDays(7)
strDateToBook = dateConvertedDateToBook.ToString("yyyy-MM-dd")
Try
Dim command As MySqlCommand = New MySqlCommand
Dim sqlQuery As String = "INSERT INTO bookings SET Date=" & "'" & strDateToBook & "',RoomID='" & strComputerRoomToBook & "',Length='" & intNewBookingLength & "',Period='" & intNewStartPeriod & "',UserID='" & intid & "'"
Dim reader As MySqlDataReader
SQLConnection.Open()
command.CommandText = sqlQuery
command.Connection = SQLConnection
reader = command.ExecuteReader
SQLConnection.Close()
Catch excep As Exception
MsgBox(excep.ToString)
End Try
Next
in my program I get an error saying "The connection property has not been set or is null"
How can I get rid of this?
It goes to the exception when it gets to SQLconnection.Open()
I created the ServerString and MySQL connection at the top of the module like so:
Dim ServerString As String = "Server=localhost;User Id=root;Password=**********;Database=rooms"
Dim SQLConnection As MySqlConnection = New MySqlConnection
You are opening a connection without its property
It should be,
Dim SQLConnection As New MySqlConnection(ServerString)
SQLConnection.Open
Also, you may want to use the USING function so that your connection is properly closed.
It seems you are just inserting a bunch of values to your database and not retrieving anything so why do you use a DataReader?
Your code should be something like this:
Using SQLConnection = New MySqlConnection(ServerString)
SQLConnection.Open 'You should open a connection only once
For RepeatBooking = 1 To 51
dateConvertedDateToBook = dateDateToBook.Date
dateDateToBook = dateDateToBook.AddDays(7)
strDateToBook = dateConvertedDateToBook.ToString("yyyy-MM-dd")
Try
Dim sqlQuery As String = "INSERT INTO bookings SET " & _
"Date='" & strDateToBook & "'," & _
"RoomID='" & strComputerRoomToBook & "', " & _
"Length='" & intNewBookingLength & "', " & _
"Period='" & intNewStartPeriod & "', " & _
"UserID='" & intid & "'"
Dim command = New MySqlCommand(sqlQuery, SQLConnection)
command.ExecuteNonQuery
Catch excep As Exception
MsgBox(excep.Message)
End Try
Next
End Using
Also, you may want to change how to pass your values into a parameter. This will prevent SQL Injection.