The connection was not closed. The connection's current state is open - vb.net

Try
If functionmode = "ADD" Then
SQLStr = "INSERT INTO boatmast VALUES ('" & gBoatType & "','" & TxtBoatCode.Text & "','" & TxtBoatName.Text & "','" & Format(txtBP.Text, "##0.#0") & "','" & Format(txtBPM.Text, "##0.#0") & "','" & Format(txtLDA.Text, "##0.#0") & "','" & , 'bpk', '" & Today & "', '" & updtime & "', 'bpk', '" & Today & "', '" & updtime & "')"
End If
conn.Open()
SQLCmd.Connection = conn
SQLCmd.CommandText = SQLStr
SQLCmd.ExecuteNonQuery()
conn.Close()
Catch ex As OdbcException
MsgBox(ex.ToString)
Finally
conn.Close()
End Try

The problem is you call conn.Close() twice. Retain your Close connection on your finally block.
Try
If functionmode = "ADD" Then
//Supposed this is you columnNAmes //Set parameters
SQLStr = "INSERT INTO boatmast (gBoatType,BoatCode,BoatName,BP, BPM,LDA,bpk,Today,updtime,bpk2,Today2,updtime2) VALUES (#gBoatType,#BoatCode,#BoatName,#BP, #BPM,#LDA,#bpk,#Today,#updtime,#bpk2,#Today2,#updtime2)"
SQLCmd.Parameters.AddWithValue("#gBoatType",gBoatType)
//DO OTHER STUFF TIL #updtime2
conn.Open()
SQLCmd.Connection = conn
SQLCmd.CommandText = SQLStr
SQLCmd.ExecuteNonQuery()
End If
Catch ex As OdbcException
MsgBox(ex.ToString)
Finally
If conn.State = ConnectionState.Open Then conn.Close()
End Try
Regards

Related

Custom date format for inserting date in mysql database

I have tried this code but the date format keeps staying the same when the record is entered
mysqlconn = New MySqlConnection
mysqlconn.ConnectionString =
Dim reader As MySqlDataReader
Try
mysqlconn.Open()
Dim query As String
query = "insert into jadco_test.adrv (id,type_adrv,date_discov,date_notif,pssd,psed,comment,hearing_date,sanction`enter code here`_sd,sanction_ed) values('" & Tbox_ID.Text & "','" & ComboBox_adrv.SelectedItem & "', '" & DateTimePicker_DD = DateTime.Now.ToString("yyyy-MM-dd") & "','" & DateTimePicker_DN.CustomFormat & "','" & DateTimePicker_pssd.CustomFormat & "','" & DateTimePicker_psed.CustomFormat & "', '" & TextBox_comment.Text & "','" & DateTimePicker_HD.CustomFormat & "','" & DateTimePicker_SSD.CustomFormat & "','" & DateTimePicker_SED.CustomFormat & "' )"
command = New MySqlCommand(query, mysqlconn)
reader = command.ExecuteReader
MessageBox.Show("record saved")
mysqlconn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
mysqlconn.Dispose()
End Try

Error Message: number of query values and destination fields are not the same in VB.net

What do you think caused the error?
It worked before I added new fields in the MS Access database, was that the cause of the error
Dim conn As New
OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\Users\JA\Documents\Sample_LogIn.accdb")
Dim insert As String = "Insert into Students values
('" & textID.Text & "', " &
"'" & textFirstName.Text & "', " &
"'" & textLastName.Text & "', " &
"'" & textPassword.Text & "')"
Dim cmd As New OleDbCommand(insert, conn)
conn.Open()
cmd.ExecuteNonQuery()
MsgBox("Successfully created new account.")
Me.Close()
Catch ex As Exception
MsgBox("Error encountered while creating new account." & vbCrLf &
"Ërror: " & ex.Message)

Missing semicolon(;) at end of SQL statement

I don't know where I should put the semicolon. Here's my code:
Try
cn.Open()
Dim query As String = "INSERT INTO CheckoutTable(PatientID,_Name,_Age,_Gender,_Phone,_Address,_Disease,_DateIN,_DateOUT,_Building,_RoomNo,_RoomType,_UnitPrice,_Status,_MASP,_Price) VALUES('" & txtPID.Text & "','" & txtName.Text & "','" & txtAge.Text & "','" & cmbGender.Text & "','" & txtPhone.Text & "','" & txtAddress.Text & "','" & txtDisease.Text & "',' " & txtDI.Text & " ',' " & txtDO.Text & " ','" & txtRT.Text & "','" & txtBuilding.Text & "','" & txtRN.Text & "',' " & txtMNS.Text & " ',' " & txtUnitPrice.Text & " ',' " & cmbStatus.Text & " ','" & txtPrice.Text & "')" & _
"DELETE From RegistrationTable where [_Name]='" & ListBox1.Text & "'" & _
"Select * from RegistrationTable"
Dim cmds As New OleDbCommand
With cmds
.CommandText = query
.Connection = cn
.ExecuteNonQuery()
End With
MsgBox("Checkout Success", MsgBoxStyle.Information)
cn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Try
cn.Open()
Dim insertQuery as String = "INSERT INTO CheckoutTable(PatientID,_Name,_Age,_Gender,_Phone,_Address,_Disease,_DateIN,_DateOUT,_Building,_RoomNo,_RoomType,_UnitPrice,_Status,_MASP,_Price) " & _
"VALUES(#PatientID, #Name, #Age, #Gender, #Phone, #Address, #Disease , #DateIn, #DateOut, #Building, #RoomNo, #RoomType, #UnitPrice, #Status, #MASP, #Price) "
Dim deleteQuery as String = "DELETE From RegistrationTable where [_Name]= #RegName "
Dim selectQuery as String = "Select * from RegistrationTable"
Dim insertCmd As New OleDbCommand
Dim deleteCmd as New OleDbCommand
With insertCmd
.Connection = cn
.CommandText = insertQuery
.Parameters.AddWithValue("#PatientID", txtPID.Text)
.Parameters.AddWithValue("#Name", txtName.Text)
.Parameters.AddWithValue("#Age", txtAge.Text)
.Parameters.AddWithValue("#Gender", cmbGender.Text)
.Parameters.AddWithValue("#Phone", txtPhone.Text)
.Parameters.AddWithValue("#Address", txtAddress.Text)
.Parameters.AddWithValue("#Disease", txtDisease.Text)
.Parameters.AddWithValue("#DateIn", txtDI.Text)
.Parameters.AddWithValue("#DateOUT", txtDO.Text)
.Parameters.AddWithValue("#Building", txtBuilding.Text)
.Parameters.AddWithValue("#RoomNo", txtRN.Text)
.Parameters.AddWithValue("#RoomType", txtRT.Text)
.Parameters.AddWithValue("#UnitPrice", txtUnitPrice.Text)
.Parameters.AddWithValue("#MASP", txtMNS.Text)
.Parameters.AddWithValue("#Status", cmbStatus.Text)
.Parameters.AddWithValue("#Price", txtPrice.Text)
.ExecuteNonQuery()
End With
With deleteCmd
.Connection = cn
.CommandText = deleteQuery
.Parameters.AddWithValue("#RegName", ListBox1.Text)
.ExecuteNonQuery()
End With
MsgBox("Checkout Success", MsgBoxStyle.Information)
cn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
#StingyJack is right, I could break your db 6 ways from sunday if I had access to your interface as you're currently not doing ANYTHING to mitigate SQL injection. In addition to parameterizing your queries to protect against injection, I removed the need to HAVE a ; at the end of each DML statement in your query, by breaking them into separate commands. The select and displaying it's results, I leave to you.

how to insert into two tables from vb.net

i want to insert two values into two tables of a sql database which i had created. In my vb.net code my problem is if i insert it get insterted but only in one table else sometimes it's not getting inside.
here is my code which i had used:
c = TextBox1.Text
sh = TextBox2.Text
ph = Val(TextBox3.Text)
ad = RichTextBox1.Text
ob = Val(TextBox4.Text)
con = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\SHOPPROJECT\SHOPPROJECT\shop.mdf;Integrated Security=True;User Instance=True")
con.Open()
str1 = " INSERT INTO CUSTOMER VALUES('" & c & " ' , '" & sh & "' ," & ph & ",'" & ad & "' ,'" & TextBox5.Text & "' ) "
str2 = "INSERT INTO BALANCE VALUES ('" & c & "', " & ob & ")"
cmd = New SqlCommand
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = str1
cmd.ExecuteNonQuery()
cmd.CommandText = str2
cmd.ExecuteNonQuery()
MsgBox("ITEM IS INSERTED", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "CUSTOMER ADDED")
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
RichTextBox1.Clear()
You can actually do it in a single command and even wrap it in a transaction like this:
str1 = "begin tran; "
str1 &= "INSERT INTO CUSTOMER VALUES('" & c & " ' , '" & sh & "' ," & ph & ",'" & ad & "' ,'" & TextBox5.Text & "' ); "
str1 &= "INSERT INTO BALANCE VALUES ('" & c & "', " & ob & "); "
str1 &= "commit tran; "
cmd = New SqlCommand
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = str1
cmd.ExecuteNonQuery()
Next you need to use try/catch on a SqlServerException to see what is going wrong. Something like:
try
' all your sql code
catch (sqlex as SqlException)
MessageBox.Show(sqlex.Message)
Also read up on SQL injection.
You don't need to use different string variable to insert the values. You can do it like this:
str1 = " INSERT INTO CUSTOMER VALUES('" & c & " ' , '" & sh & "' ," & ph & ",'" & ad & "' ,'" & TextBox5.Text & "' );"
str1 & = "INSERT INTO BALANCE VALUES ('" & c & "', " & ob & ")"
cmd = New SqlCommand
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = str1
cmd.ExecuteNonQuery()

SQL statement won't insert into DB.sdf

I am using Visual Studio 2008 and have connected a database correctly as I have done a login that works fine, although when I try to insert information submitted in the text boxes a different table, it doesn't enter after I end program to check it still has no data in. Any ideas?
Dim con As SqlCeConnection = New SqlCeConnection("Data Source=NESdb.sdf")
Dim myDA As SqlCeDataAdapter
Dim myDataSet As DataSet
Dim dt As New DataTable()
'Connect to database'
con.Open()
'Attempt to retrieve data'
Try ' Select username and password that match'
Dim cmd As SqlCeDataAdapter = New SqlCeDataAdapter("INSERT INTO ScrapVehicles(Fname, Lname, Add1, Add2, Town, PostCode, Telephone, Mob, Email, VehicleType, RegNo, Year, Make, Model, V5, Collected, CollectionDate)" + "VALUES('" & txtFname.Text & "', '" & txtLname.Text & "', '" & txtAdd1.Text & "', '" & txtAdd2.Text & "', '" & txtTown.Text & "', '" & txtPostCode.Text & "', '" & txtTelephone.Text & "', '" & txtMob.Text & "', '" & txtEmail.Text & "', '" & comboVehicleType.Text & "', '" & txtReg.Text & "', '" & comboYear.Text & "', '" & comboMake.Text & "', '" & txtModel.Text & "', '" & chkV5.Text & "', '" & chkCollected.Text & "', '" & dtpWhen.Text & "')", con)
'Catch errors'
Catch ex As Exception
End Try
'Close connection to database'
If con.State <> ConnectionState.Closed Then
con.Close()
End If
You're building up the cmd object, but you don't execute it.
Suggest ditch the Adapter when inserting. Try this instead:
/*snipped values for brevity.*/
Dim insertSql As String = "INSERT INTO ScrapVehicles(Fname, Lname, Add1, Add2, Town) VALUES(#FName, #LName, #Add1, #Add2, #Town)"
conn.Open()
Dim cmd As New SqlCeCommand(insertSql, conn)
cmd.Parameters.Add(New SqlCeParameter("#FName", txtFirstName.Text.Trim()))
cmd.Parameters.Add(New SqlCeParameter("#LName", txtLastName.Text.Trim()))
cmd.Parameters.Add(New SqlCeParameter("#Add1", txtAdd1.Text.Trim()))
cmd.Parameters.Add(New SqlCeParameter("#Add2", txtAdd2.Text.Trim()))
cmd.ExecuteNonQuery()
conn.Close()
You are missing a bracket at the end
& dtpWhen.Text & "'", con)
should be
& dtpWhen.Text & "')", con)
Instead of using a SqlCeDataAdapter, use a SqlCeCommand object. And after creating it, actually use it (call ExecuteNonQuery on it). And remove the Try, Catch Ex as Exception and End Try lines so that, if an error occurs, you'll actually see it.
That's what I can see from 30 seconds of looking.
Edit
You should also look at using parameters rather than concatenating the INSERT statement together.