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()
Related
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
I have declared sql, cmd and cnt on public class, and also i have declare my database on Module.
Dim sql As String
Dim cmd As OleDb.OleDbCommand
Dim cnt As Long
Try
sql = "UPDATE [LDF] SET [Group_Code] = '" & ComboBox1.Text & "',
[Loan_Disb] ='" & TextBox1.Text & "',
[No_Of_Instalment] = '" & ComboBox2.Text & "',
[Single_Instalment]='" & TextBox2.Text & "',
[Loan_Security]='" & TextBox3.Text & "',
[Total_Amnt_TR]='" & TextBox4.Text & "',
[Member_Name]='" & TextBox5.Text & "',
[Group_Name]='" & TextBox6.Text & "',
[Date_Of_Disb]='" & DateTimePicker1.Value & "'
WHERE [Member_Number] = ' & ComboBox3.Text & '"
cmd = New OleDb.OleDbCommand(sql, Con)
cnt = cmd.ExecuteNonQuery
MsgBox("RECORD HAVE SUCCESSFUL UPDATED")
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
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.
I have a VB.Net form which allows the user to update the customer details such as name, contact no:, etc. So when the customer enters the new name for the customer name etc. the application should update the corresponding field in the existing entry that relates to the customer ID.
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim adapter As New SqlDataAdapter
Dim dt As New DataTable
cn.ConnectionString = ("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cmd.Connection = cn
cn.Open()
cmd.CommandText = " UPDATE TblCustomerDetails (compID, compName, compContact, compAddress, compFax, compEmail, compPayterm, compTaxscheme, compPaymode, compRemarks ) SET Values ('" & lblCID.Text & "', '" & txtCname.Text & "', '" & txtCpno.Text & "', '" & txtCaddrs.Text & "','" & txtCfax.Text & "', '" & txtCemail.Text & "', '" & cmbPterm.Text & "','" & cmbTaxschm.Text & "',' " & cmbPmode.Text & "', '" & txtRemarks.Text & "') WHERE compID = '" & lblCID.Text & "';"
cmd.ExecuteNonQuery()
MsgBox("Account updated!!", MsgBoxStyle.Information, "Updation complete")
Your using a INSERT syntax for your UPDATE statement. Your UPDATE statement should have the form:
UPDATE tableName
SET col1 = val1,
col2 = val2,
col3 = val3
WHERE someColumn = someValue
Additionally, you are wide open to SQL Injection attacks by using non-parameterized queries. Finally, I would use a Using blocks to ensure your connection and command are properly closed and disposed of.
Putting it all together it would look something like this:
Using Dim cn As SqlConnection = New SqlConnection("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cn.Open()
Dim sqlQuery As String = "UPDATE TblCustomerDetails " + _
"SET compName = #compName, " + _
"compContact = #compContact, " + _
"compAddress = #compAddress, " + _
"compFax = #compFax, " + _
"compEmail = #compEmail, " + _
"compPayterm = #compPayterm, " + _
"compTaxscheme = #compTaxscheme, " + _
"compPaymode = #compPaymode, " + _
"compRemarks = #compRemarks " + _
"WHERE compID = #compID"
Using Dim cmd As SqlCommand = New SqlCommand(sqlQuery, cn)
cmd.Parameters.AddWithValue("#compFax", txtCname.Text)
cmd.Parameters.AddWithValue("#compContact", txtCpno.Text)
cmd.Parameters.AddWithValue("#compAddress", txtCaddrs.Text)
cmd.Parameters.AddWithValue("#compFax", txtCfax.Text)
cmd.Parameters.AddWithValue("#compEmail", txtCemail.Text)
cmd.Parameters.AddWithValue("#compPayterm", cmbPTerm.Text)
cmd.Parameters.AddWithValue("#compTaxscheme", cmbTaxschm.Text)
cmd.Parameters.AddWithValue("#compPaymode", cmbPmode.Text)
cmd.Parameters.AddWithValue("#compRemarks", txtRemarks.Text)
cmd.Parameters.AddWithValue("#compID", lblCID.Text)
Dim result As Integer
result = cmd.ExecuteNonQuery()
If result = 1 Then
MsgBox("Account updated!!", MsgBoxStyle.Information, _
"Updation complete")
Else
MsgBox("Account not updated!!", MsgBoxStyle.Information, _
"Updation not complete")
End If
End Using
End Using
There are a few more things to note in the above code sample:
First, I removed compID from the list of values to update. You're using that in your WHERE query, so I think you would have interesting results in your query if you're trying to update the same column you are using as part of your WHERE clause. Additionally, the source for that value is a Label, which tells me it's not supposed to be changed.
Secondly, ExecuteNonQuery() returns an int with the number of rows affected. In this case, it should be 1 - if it's not 1, I have you show a different message box.
Thirdly, cmbPTerm, cmbTaxxshm and cmbPmode sound like ComboBox to me, and you're not going to get what I think you're expecting using their Text property. I think you'll want SelectedText - hard to say without knowning how your ComboBoxes are bound. I'll leave that as an exercise for you :)
Fourth, I broke the UPDATE query up across several lines simply for readability - you don't have to do it that way, as long as the query is correct.
Finally, I'd suggest using MessagBox.Show() vs MsgBox.
Dim cnn As New SqlConnection
Dim cmd As New SqlCommand
cnn.ConnectionString = ("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cmd.Connection = cnn
cnn.Open()
cmd.CommandText = "update TblCustomerDetails set compName='" & txtCname.Text & "' , compContact = '" & txtCpno.Text & "' , compAddress = '" & txtCaddrs.Text & "' , compFax = '" & txtCfax.Text & "' , compEmail = '" & txtCemail.Text & "' , compPayterm = '" & cmbPterm.Text & "' , compTaxscheme = '" & cmbTaxschm.Text & "' , compPaymode = '" & cmbPmode.Text & "' , compRemarks = '" & txtRemarks.Text & "' where compID = '" & lblCID.Text & "'"
cmd.ExecuteNonQuery()
cnn.Close()
MessageBox.Show("entry updated!!!")
i have some trobles in updating my database. ihave this codes :
Dim cmd As OleDbCommand
Dim sql As String
sql = "UPDATE nmat SET nip = '" & lblNipDosen.Text & "', nim = '" & TxtNIM.Text & "', ntugas = '" & TxtNtugas.Text & "', nabsensi = '" & TxtNabsen.Text & "', nuts = '" & TxtNuts.Text & "', nuas = '" & TxtNuas.Text & "' WHERE nim='" & TxtNIM.Text & "'"
conn.Open()
Dim reader As OleDbDataReader
Try
cmd = New OleDbCommand(sql, conn)
cmd.ExecuteNonQuery()
DataGridView1.Refresh()
Finally
'reader.Close()
End Try
conn.Close()
my problem is, by these code, the grid can be refreshed after i close and open this form again. but if i check in my ms Access, the data was not chanded at all. how to update my database and showed in my datagrid??
Try This :
Dim cmd As OleDbCommand
Dim rstTable As New DataTable()
Dim sql As String
sql = "UPDATE nmat SET nip = '" & lblNipDosen.Text & "', nim = '" & TxtNIM.Text & "', ntugas = '" & TxtNtugas.Text & "', nabsensi = '" & TxtNabsen.Text & "', nuts = '" & TxtNuts.Text & "', nuas = '" & TxtNuas.Text & "' WHERE nim='" & TxtNIM.Text & "'"
conn.Open()
Dim reader As OleDbDataReader
Try
cmd = New OleDbCommand(sql, conn)
rstTable.Load(cmd.ExecuteReader())
DataGridView1.DataSource =rstTable
Finally
'reader.Close()
End Try
conn.Close()
your gridview columns should have bound to a field