datagridview update to database - sql

please help me...
I load my database in the datagrid view and edit some cells.
Now I just need to update my database
here are my codes
Dim dT As DataTable = MyDB.ExecCommand("SELECT `Field Name` FROM `tblfield`", "wellsfargo").Tables(0)
Dim sSQL As String = ""
Dim dZ As DataTable = MyDB.ExecCommand("SELECT " & sColumn & " FROM `" + cboJob.Text.Trim + "`", "wellsfargo", 0).Tables(0)
dColumn = New DataTable
dColumn = MyDB.ExecCommand("SHOW COLUMNS IN tblrecord", "wellsfargo", 0).Tables(0)
If dZ.Rows.Count <> 0 Then
sSQL = "UPDATE " & sColumn & " FROM `" + cboJob.Text.Trim + "`"
MyDB.ExecQuery(sSQL, "wellsfargo")
Else
Dim sColumn As String = ""
For z As Integer = 0 To dT.Rows.Count - 1
If z = 0 Then
sColumn = "`" & dT.Rows(z).Item(0).ToString & "`"
Else
sColumn = sColumn & ",`" & dT.Rows(z).Item(0).ToString & "`"
End If
Next
sSQL = "INSERT INTO `" + MyJob + "` (" + sColumn + ") "
MyDB.ExecQuery(sSQL, "wellsfargo")
End If

Done.
I used this codes..
Try
Cursor = Cursors.WaitCursor
Dim sSQL As String
sSQL = "UPDATE `" + cboJob.Text.Trim + "` SET `Description` ='" + TextBox1.Text + "' WHERE `Description`= '" + Label2.Text + "' AND `Line Number` ='" + comList.Text + "'"
MyDB.ExecQuery(sSQL, "wellsfargo")
MsgBox("Updated!")
btnUpdate.Enabled = False
Catch ex As Exception
MsgBox("Select table first to Update")
End Try
Cursor = Cursors.Default

Related

MS Access rst.MoveNext not Moving to next record

I am using the code below to run through a table of payments and apply those payments to available balances. I keep having trouble where it will not move to the next payment.
Sometimes it will loop through payments, most times it will try to run the same payment again which causes an error since the payment is already used.
Public Sub applyPaymentsFunction(ByVal PaymentDate As String)
Dim dbs As Database
Dim rst As DAO.Recordset
Dim qry As String
Dim printedList As DAO.Recordset
Set dbs = CurrentDb
Set printedList = dbs.OpenRecordset("000AppliedPayments")
qry = "SELECT * FROM ReceivePayment WHERE (UnusedPayment > 0) AND TxnDate = #" + PaymentDate + "#"
Set rst = CurrentDb.OpenRecordset(qry)
If rst.RecordCount > 0 Then
rst.MoveFirst
Do
Debug.Print (rst("TxnID"))
printedList.AddNew
printedList!accountNumber = rst("CustomerRefFullName")
printedList!Date = rst("TxnDate")
printedList!Payment = rst("TotalAmount")
printedList!AmountLeft = rst("UnusedPayment")
printedList.Update
Call applyPaymentsFunction2(rst("CustomerRefListID"), rst("TxnId"), rst("UnusedPayment"))
rst.MoveNext
Loop Until rst.EOF = True
rst.Close
End If
End Sub
Public Sub applyPaymentsFunction2(ByVal CustomerRefListID As String, ByVal PaymentTxnID As String, ByVal thisPayment As Integer)
Dim dbs As Database
Dim custrst As DAO.Recordset
Dim getCharges As String
Dim availPayment As Integer
Set dbs = CurrentDb
availPayment = thisPayment
getCharges = "SELECT TxnDate, TxnID, BalanceRemaining, Desc AS thisThing FROM Charge WHERE (CustomerRefListID = '" + CustomerRefListID + "'"
getInvoices = "SELECT TxnDate, TxnID, BalanceRemaining, InvoiceLineDesc as thisThing FROM InvoiceLine WHERE (CustomerRefListID = '" + CustomerRefListID + "'"
getCust = "SELECT * FROM Customer Where ParentRefListID = '" + CustomerRefListID + "'"
Set custrst = CurrentDb.OpenRecordset(getCust)
If custrst.RecordCount > 0 Then
custrst.MoveFirst
Do
getCharges = getCharges + " OR CustomerRefListID = '" + custrst("ListId") + "'"
getInvoices = getInvoices + " OR CustomerRefListID = '" + custrst("ListId") + "'"
custrst.MoveNext
Loop Until custrst.EOF = True
custrst.Close
End If
getCharges = getCharges + ") AND (BalanceRemaining > 0)"
getInvoices = getInvoices + ") AND (BalanceRemaining > 0)"
joinedChargeInvoice = getCharges + "UNION ALL " + getInvoices + "ORDER BY TxnDate ASC"
Set chargesrst = CurrentDb.OpenRecordset(joinedChargeInvoice)
If chargesrst.RecordCount > 0 Then
chargesrst.MoveFirst
Do
If availPayment = 0 Then
Exit Sub
ElseIf availPayment = chargesrst("BalanceRemaining") Then
Debug.Print ("INSERT INTO ReceivePaymentLine (TxnID, AppliedToTxnTxnID, AppliedToTxnPaymentAmount) VALUES ('" + PaymentTxnID + "', '" + chargesrst("TxnID") + "', " + Format(availPayment, "0.00") + " )")
DoCmd.RunSQL ("INSERT INTO ReceivePaymentLine (TxnID, AppliedToTxnTxnID, AppliedToTxnPaymentAmount) VALUES ('" + PaymentTxnID + "', '" + chargesrst("TxnID") + "', " + Format(availPayment, "0.00") + " )")
availPayment = 0
Exit Sub
ElseIf availPayment < chargesrst("BalanceRemaining") Then
Debug.Print ("INSERT INTO ReceivePaymentLine (TxnID, AppliedToTxnTxnID, AppliedToTxnPaymentAmount) VALUES ('" + PaymentTxnID + "', '" + chargesrst("TxnID") + "', " + Format(availPayment, "0.00") + " )")
DoCmd.RunSQL ("INSERT INTO ReceivePaymentLine (TxnID, AppliedToTxnTxnID, AppliedToTxnPaymentAmount) VALUES ('" + PaymentTxnID + "', '" + chargesrst("TxnID") + "', " + Format(availPayment, "0.00") + " )")
availPayment = 0
Exit Sub
ElseIf availPayment > chargesrst("BalanceRemaining") Then
Debug.Print ("INSERT INTO ReceivePaymentLine (TxnID, AppliedToTxnTxnID, AppliedToTxnPaymentAmount) VALUES ('" + PaymentTxnID + "', '" + chargesrst("TxnID") + "', " + Format(chargesrst("BalanceRemaining"), "0.00") + " )")
DoCmd.RunSQL ("INSERT INTO ReceivePaymentLine (TxnID, AppliedToTxnTxnID, AppliedToTxnPaymentAmount) VALUES ('" + PaymentTxnID + "', '" + chargesrst("TxnID") + "', " + Format(chargesrst("BalanceRemaining"), "0.00") + " )")
availPayment = availPayment - chargesrst("BalanceRemaining")
End If
chargesrst.MoveNext
Loop Until chargesrst.EOF = True Or availPayment = 0
chargesrst.Close
End If
End Sub
i have tried rst.MoveNext and rst.Move(1)
i have tried with and without the Exit Sub
i have tried 1 big query, and broken up into these two where it calls a separate sub
I am pretty sure that the problem lies in the Exit Sub statements in your secondary subroutine. When you hit these, you are not closing the open recordset chargerst.
Admittedly it is a very long time since I programmed DAO in VBA, but I am sure there is a problem if you exit a subroutine leaving a recordset open and returning to a main routine. Please try always closing the chargerst recordset before calling Exit Sub

Updating SQL Table via VBA cuts off decimals

I need to update a set of values from an Excel Worksheet into a SQL Server Table.
This is the Excel Table:
I wrote some code in VBA to do this, but I'm not very expert.
The update work just fine except for the part where it truncate decimals.
As you can see the decimals get cuts off. The fields on SQL are declared as Decimal (19,5).
Sure there's something wrong in the VBA code. Here's my code.
On Error GoTo RigaErrore
Dim cn_ADO As Object
Dim cmd_ADO As Object
Dim SQLUser As String
Dim SQLPassword As String
Dim SQLServer As String
Dim DBName As String
Dim DBConn As String
Dim SQLQuery As String
Dim strWhere As String
Dim i As Integer
Dim jOffset As Integer
Dim iStartRow As Integer
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'iStep = 100
jOffset = 20
iStartRow = 3
i = iStartRow
SQLUser = "xxxx"
SQLPassword = "xxx"
SQLServer = "xxxxxxxx"
DBName = "xxxxx"
DBConn = "Provider=SQLOLEDB.1;Pesist Security Info=True;User ID=" & SQLUser & ";Password=" & SQLPassword & ";Initial Catalog=" & DBName & ";" & _
"Data Source=" & SQLServer & ";DataTypeCompatibility=80;"
Set cn_ADO = CreateObject("ADODB.Connection")
cn_ADO.Open DBConn
Set cmd_ADO = CreateObject("ADODB.Command")
While Cells(i, jOffset).Value <> ""
xlsIDKey = Cells(i, 0 + jOffset)
xlsVendSim = CDbl(Cells(i, 1 + jOffset))
xlsOreSim = CDbl(Cells(i, 2 + jOffset))
xlsProdVar = CDbl(Cells(i, 3 + jOffset))
xlsOreSimVar = CDbl(Cells(i, 4 + jOffset))
strWhere = "ID_KEY = '" & xlsIDKey & "'"
SQLQuery = "UPDATE DatiSimulati " & _
"SET " & _
"VEND_SIM = Cast(('" & xlsVendSim & "') as decimal (19,5)), " & _
"ORE_SIM = Cast(('" & xlsOreSim & "') as decimal (19,5)), " & _
"PROD_VAR = Cast(('" & xlsProdVar & "') as decimal (19,5)), " & _
"ORE_SIM_VAR = Cast(('" & xlsOreSimVar & "') as decimal (19,5)) " & _
"WHERE " & strWhere
cmd_ADO.CommandText = SQLQuery
cmd_ADO.ActiveConnection = cn_ADO
cmd_ADO.Execute
i = i + 1
Wend
Set cmd_ADO = Nothing
Set cn_ADO = Nothing
Exit Sub
RigaErrore:
MsgBox Err.Number & vbNewLine & Err.Description
Application.StatusBar = False
Application.Cursor = xlDefault
If Not cn_ADO Is Nothing Then
Set cn_ADO = Nothing
End If
If Not cmd_ADO Is Nothing Then
Set cmd_ADO = Nothing
End If
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Thanks everybody who could help solve this.
A work-around would be to replace the decimal commas with dots.
Option Explicit
Sub connectDB()
Const SQLUser = "#"
Const SQLPassword = "#"
Const SQLServer = "#"
Const DBName = "#"
Dim DBConn As String
DBConn = "Provider=SQLOLEDB.1;Pesist Security Info=True" & _
";User ID=" & SQLUser & ";Password=" & SQLPassword & _
";Initial Catalog=" & DBName & _
";Data Source=" & SQLServer & _
";DataTypeCompatibility=80;"
Dim cn_ADO As Object, cmd_ADO As Object
Set cn_ADO = CreateObject("ADODB.Connection")
cn_ADO.Open DBConn
Set cmd_ADO = CreateObject("ADODB.Command")
cmd_ADO.ActiveConnection = cn_ADO
Const joffset = 20
Const iStartRow = 3
Dim SQLQuery As String, sIDKey As String
Dim sVendSim As String, sOreSim As String
Dim sProdVar As String, sOreSimVar As String
Dim i As Long
i = iStartRow
' create log file
Dim LOGFILE As String
LOGFILE = ThisWorkbook.Path & "\logfile.txt"
Dim fs As Object, ts As Object
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.CreateTextFile(LOGFILE, True)
While Len(Cells(i, joffset).Value) > 0
sIDKey = Cells(i, 0 + joffset)
sVendSim = Replace(Cells(i, 1 + joffset), ",", ".")
sOreSim = Replace(Cells(i, 2 + joffset), ",", ".")
sProdVar = Replace(Cells(i, 3 + joffset), ",", ".")
sOreSimVar = Replace(Cells(i, 4 + joffset), ",", ".")
SQLQuery = "UPDATE DatiSimulati " & _
"SET " & _
"VEND_SIM = " & sVendSim & ", " & _
"ORE_SIM = " & sOreSim & ", " & _
"PROD_VAR = " & sProdVar & ", " & _
"ORE_SIM_VAR = " & sOreSimVar & " " & _
"WHERE ID_KEY = " & sIDKey
ts.writeline SQLQuery & vbCr
cmd_ADO.CommandText = SQLQuery
cmd_ADO.Execute
i = i + 1
Wend
ts.Close
MsgBox i - iStartRow & " records updated see " & LOGFILE, vbInformation
End Sub

Access dynamic filtering listbox with double where clause

I've got a dynamic textbox filtering function in VBA
Dim sSQL As String
sSQL = "SELECT qry_allUtilities.ID, qry_allUtilities.Supplier AS Lieferant, qry_allUtilities.Cabinet AS Ablageort, qry_allUtilities.Size AS Grösse, qry_allUtilities.WorkingLength AS Nutzlänge, qry_allUtilities.Description AS Bezeichnung "
sSQL = sSQL & " FROM qry_allUtilities "
If Not sFilter = "" Then
Dim arrFilter
arrFilter = Split(sFilter, "+")
Dim varWort
For Each varWort In arrFilter
If Not varWort = "" Then
Dim sWort As String
sWort = varWort
sSQL = sSQL & " AND [ID] & ' ' & [Supplier] & ' ' & [Floor] & ' ' & [Cabinet] & ' ' & [Size] & ' ' & [WorkingLength] LIKE '*" & sWort & "*'"
End If
Next
sSQL = Replace(sSQL, " AND ", " WHERE ", 1, 1, vbTextCompare)
End If
ctlListe.RowSource = sSQL
and would like to extend this with another WHERE clause because I have to exclude the records with qry_allUtilities.InActive=False
How do I do this? I always keep getting null or it won't exclude the records with InActive=True :/
I usually do this to add a variable (but unknown) number of filter options:
strFilter = "" ' build the filter string in here
if <first condition reason is true> then
strFilter = strFilter + first condition + " AND "
end if
if <second condition reason is true> then
strFilter = strFilter + <second condition> + " AND "
end if
' finish up
if len(strFilter) > 0 then ' some critera are valid
strFilter = Left(strFilter, Len(strFilter) - 5) ' chop off the spare " AND "
strFilter = " WHERE " + strFilter ' put the " WHERE " on the front
' else ' no where clause
end if
Note that the spaces either side of the " AND " and " WHERE " are important.

Need Help for Updating database in vb.net

Someone knows why I got an exception when the code running at cmd.ExecuteNonQuery()? when I update Date, it runs perfectly but when I update the Finish date, I got that error.
This is the code
Call connection()
If txt_UpCom.Text = "" Or cbCom.SelectedItem = "" Then
If txt_ComNew.Enabled = True Then
MessageBox.Show("Please fill the entire data!")
End If
Else
Try
Dim str As String
If cbCom.SelectedItem = "Date" Or cbCom.SelectedItem = "Finish Date" Then
Dim comdate As String = dateCom.Value.ToString("yyyy-MM-dd")
str = "UPDATE complain SET " & cbCom.SelectedItem & "= '" & comdate & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
Else
str = "UPDATE complain SET " & cbCom.SelectedItem & " = '" & txt_ComNew.Text & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
End If
cmd = New MySql.Data.MySqlClient.MySqlCommand(str, conn)
cmd.ExecuteNonQuery()
msgBoxSuccess.ShowDialog()
conn.Close()
Catch ex As Exception
MessageBox.Show("Unable to Update")
End Try
End If
This is the table in database
As #Jacek Wróbel mentioned in the comments, you should keep the column names between [] (square brackets) or "" (double quots). The same thing goes for table names (or any other SQL objects for that matter).
Long story short, change this part of your code:
If cbCom.SelectedItem = "Date" Or cbCom.SelectedItem = "Finish Date" Then
Dim comdate As String = dateCom.Value.ToString("yyyy-MM-dd")
str = "UPDATE complain SET " & cbCom.SelectedItem & "= '" & comdate & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
Else
str = "UPDATE complain SET " & cbCom.SelectedItem & " = '" & txt_ComNew.Text & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
End If
to this:
If cbCom.SelectedItem = "Date" Or cbCom.SelectedItem = "Finish Date" Then
Dim comdate As String = dateCom.Value.ToString("yyyy-MM-dd")
str = "UPDATE `complain` SET `" & cbCom.SelectedItem & "` = '" & comdate & "' WHERE `ComplainID` = '" & txt_UpCom.Text & "'"
Else
str = "UPDATE `complain` SET `" & cbCom.SelectedItem & "` = '" & txt_ComNew.Text & "' WHERE `ComplainID` = '" & txt_UpCom.Text & "'"
End If
Note: I prefer to keep things consistant, so I added [] to each object whether it contains spaces or not.

want to update record if exists and insert if not exists

want to update record if exists and insert if not exists into vsolv_trn_tsalesregdump Is tsalesregdump_name is unique in table vsolv_trn_tsalesregdump
when i click check box that particular row should be check on other table and how to use it for loop in form loop i can use the "tsalesdump_date,tsalesdump_name,executivename_executive" this three if the value is same its go to update and otherwise its not to same its move on insert how can i write it can any 1help me
if i have use two table one temp and other 1 is orginal\ temp table =vsolv_tmp_tsalesdump orginal table=vsolv_trn_tsalesregdump.
if already i hav save the data in orginal table,again if i hav assing data for temp table and view in radgrid if select and submit the button its go to check on orginal table if the value is already there its update it otherwise insert how can use it
Protected Sub btn_Submit_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btn_Submit.Click
lblerrmsg.Text = ""
Dim chk As CheckBox
Dim lbtn As LinkButton
Dim Res As Long
Dim lobjrow As DataRow
Dim lObjErrTable As New DataTable
Dim a As Integer = 0
Dim dtcarbooking As New DataTable
Dim dtDumpBooking As New DataTable
Dim lsRefid As String = String.Empty
Dim dtdumpsample As New DataTable
Dim name As String = String.Empty
If Check_Validation() = True Then
Exit Sub
End If
Gobjdbconn.OpenConn()
lObjErrTable = Error_TabelFill()
For i As Integer = 0 To GVUpload.Items.Count - 1
chk = GVUpload.Items(i).FindControl("chkupload")
If chk.Checked = True Then
lsRefid = GVUpload.Items(i).GetDataKeyValue("tsalesdump_gid").ToString()
MsSql = ""
MsSql &= "Select tsalesdump_gid,tsalesdump_date,tsalesdump_name,executivename_executive,tsalesdump_vch_no,tsalesdump_debit,tsalesdump_credit"
MsSql &= " from vsolv_tmp_tsalesdump as a"
MsSql &= " left join vsolv_trn_executivename as b on a.tsalesdump_name = b.executivename_particulars"
MsSql &= " where tsalesdump_gid = '" & lsRefid & "' and tsalesdump_isremoved = 'N'"
dtDumpBooking = Gobjdbconn.GetDataTable(MsSql)
MsSql = ""
MsSql &= "Insert into vsolv_trn_tsalesregdump(tsalesregdump_date,tsalesregdump_name,tsalesregdump_executive,tsalesregdump_vch_no"
MsSql &= " ,tsalesregdump_debit,tsalesregdump_credit,tsalesregdump_importby)"
MsSql &= " Values ('" & Format(CDate(dtDumpBooking.Rows(0).Item("tsalesdump_date")), "yyyy-MMM-dd").ToString() & "'"
MsSql &= ",'" & dtDumpBooking.Rows(0).Item("tsalesdump_name").ToString() & "'"
MsSql &= ",'" & dtDumpBooking.Rows(0).Item("executivename_executive").ToString() & "'"
MsSql &= " ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_vch_no").ToString() & "'"
MsSql &= " ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_debit").ToString() & "','" & dtDumpBooking.Rows(0).Item("tsalesdump_credit").ToString() & "','SIVA')"
MnResult = Gobjdbconn.ExecuteNonQuerySQL(MsSql)
If MnResult = 1 Then
MsSql = ""
MsSql &= " Delete from vsolv_tmp_tsalesdump where tsalesdump_gid = '" & lsRefid & "'"
Gobjdbconn.ExecuteNonQuerySQL(MsSql)
Else
lobjrow = lObjErrTable.NewRow()
a = a + 1
lobjrow("Sno") = a
lobjrow("Booking Ref No") = dtcarbooking.Rows(0).Item("tsalesregdump_name").ToString
lobjrow("Description") = "Duplicate Record"
lObjErrTable.Rows.Add(lobjrow)
End If
End If
Next
POPSummary()
If Not lObjErrTable Is Nothing Then
If lObjErrTable.Rows.Count > 0 Then
Call Pop_Data(lObjErrTable)
End If
End If
End Sub
If you want to update record if already exists else insert in SQL then you can achieve by following: You need to change MsSql string for Insert command
MsSql = "" + _
"IF EXISTS(Select tsalesregdump_name From vsolv_trn_tsalesregdump Where tsalesregdump_name = '" & dtDumpBooking.Rows(0).Item("tsalesdump_name").ToString() & "') " + _
"BEGIN " + _
" Update vsolv_trn_tsalesregdump " + _
" Set tsalesregdump_date = '" & Format(CDate(dtDumpBooking.Rows(0).Item("tsalesdump_date")), "yyyy-MMM-dd").ToString() & "' " + _
" ,tsalesregdump_executive = '" & dtDumpBooking.Rows(0).Item("executivename_executive").ToString() & "' " + _
" ,tsalesregdump_vch_no = '" & dtDumpBooking.Rows(0).Item("tsalesdump_vch_no").ToString() & "' " + _
" ,tsalesregdump_debit = '" & dtDumpBooking.Rows(0).Item("tsalesdump_debit").ToString() & "' " + _
" ,tsalesregdump_credit = '" & dtDumpBooking.Rows(0).Item("tsalesdump_credit").ToString() & "' " + _
" ,tsalesregdump_importby = 'SIVA' " + _
" Where tsalesregdump_name = '" & dtDumpBooking.Rows(0).Item("tsalesdump_name").ToString() & "' " + _
"END " + _
"ELSE " + _
"BEGIN " + _
" Insert into vsolv_trn_tsalesregdump(tsalesregdump_date,tsalesregdump_name,tsalesregdump_executive,tsalesregdump_vch_no " + _
" ,tsalesregdump_debit,tsalesregdump_credit,tsalesregdump_importby) " + _
" Values ('" & Format(CDate(dtDumpBooking.Rows(0).Item("tsalesdump_date")), "yyyy-MMM-dd").ToString() & "' " + _
" ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_name").ToString() & "' " + _
" ,'" & dtDumpBooking.Rows(0).Item("executivename_executive").ToString() & "' " + _
" ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_vch_no").ToString() & "' " + _
" ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_debit").ToString() & "','" & dtDumpBooking.Rows(0).Item("tsalesdump_credit").ToString() & "','SIVA') " + _
"END "
MnResult = Gobjdbconn.ExecuteNonQuerySQL(MsSql)
I am assuming here that tsalesregdump_name is unique.