command error *incorrect syntax near ','* - sql-server-2008-r2

Dim Query As String
Dim con As SqlConnection = New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=Minimarket;Integrated Security=True")
Query = "INSERT INTO Barang(kode_bar,kode_kat,nama_bar,satuan, hbeli, hjual, stok, expired)VALUES("
Query = Query + txtkodebar.Text + ",'" + cmbkodekat.Text + "','" + txtnamabar.Text + "','" + txtsatuan.Text + "','" + txthbeli.Text + "','" + txthjual.Text + "','" + txtstok.Text + "','" + Format(dtpex.Text, "yyyy-MM-dd HH:mm:ss") + "'"
con.Open()
Dim cmd As SqlCommand = New SqlCommand(Query, con)
Dim i As Integer = cmd.ExecuteNonQuery()
If (i > 0) Then
MessageBox.Show("Data berhasil disimpan")
Else
MessageBox.Show("Data gagal disimpan")
End If
con.Close()
*there is anyone can help me ? when i press button save there is error incorrect syntax near ',' in cmd.executenonquery . what i must doing now ? i fell give up :'( *

The reason you are getting that error is this part of your query:
Query = Query + txtkodebar.Text + ",'"
This results in no quotes around txtkodebar.Text. You could fix this by changing it to this:
Query = Query + "'" + txtkodebar.Text + "','"
but a far better way to fix this would be to use parameterized queries, which would not only make this query much less prone to errors, it also eliminates a very bad security hole you have here. What would happen if someone passed "dummy','2015-01-01');DROP DATABASE;" into txtstok.Text?

You are missing a space between expired) and VALUES, you are also missing quotes around txtkodebar.Text, see corrected codebelow:
Dim Query As String
Dim con As SqlConnection = New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=Minimarket;Integrated Security=True")
Query = "INSERT INTO Barang(kode_bar,kode_kat,nama_bar,satuan, hbeli, hjual, stok, expired) VALUES("
Query = Query + "'" + txtkodebar.Text + "','" + cmbkodekat.Text + "','" + txtnamabar.Text + "','" + txtsatuan.Text + "','" + txthbeli.Text + "','" + txthjual.Text + "','" + txtstok.Text + "','" + Format(dtpex.Text, "yyyy-MM-dd HH:mm:ss") + "')"
con.Open()
Dim cmd As SqlCommand = New SqlCommand(Query, con)
Dim i As Integer = cmd.ExecuteNonQuery()
If (i > 0) Then
MessageBox.Show("Data berhasil disimpan")
Else
MessageBox.Show("Data gagal disimpan")
End If
con.Close()
As stated by #GarethD, you should also read upon parametrised queries, as your current query is vulnerable to SQL injection.

The chances are you have something like O'shea in one of your text boxes, which means that because you are using string concatenation to build your query string rather than parameters you end up with an incorrect string.
If you switch to using proper parameterised queries, you will remove the chances of this happening, and will send a properly formatted SQL Statement to the server:
Dim Query As String
Query = "INSERT INTO Barang(kode_bar,kode_kat,nama_bar,satuan, hbeli, hjual, stok, expired)" & _
"VALUES(#kode_bar,#kode_kat,#nama_bar,#satuan, #hbeli, #hjual, #stok, #expired)"
Using conn As New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=Minimarket;Integrated Security=True")
Using cmd As New SqlCommand(Query, conn)
cmd.Parameters.Add("#kode_bar", SqlDbType.Int).Value = txtkodebar.Text
cmd.Parameters.Add("#kode_kat", SqlDbType.VarChar, 50).Value = cmbkodekat.Text
cmd.Parameters.Add("#nama_bar", SqlDbType.VarChar, 50).Value = txtnamabar.Text
cmd.Parameters.Add("#satuan", SqlDbType.VarChar, 50).Value = txtsatuan.Text
cmd.Parameters.Add("#hbeli", SqlDbType.VarChar, 50).Value = txthbeli.Text
cmd.Parameters.Add("#hjual", SqlDbType.VarChar, 50).Value = txthjual.Text
cmd.Parameters.Add("#stok", SqlDbType.VarChar, 50).Value = txtstok.Text
cmd.Parameters.Add("#expired", SqlDbType.DateTime).Value = DateTime.ParseExact(dtpex.Text, "yyyy-MM-dd HH:mm:ss", Nothing)
conn.Open()
Dim i As Integer = cmd.ExecuteNonQuery()
If (i > 0) Then
MessageBox.Show("Data berhasil disimpan")
Else
MessageBox.Show("Data gagal disimpan")
End If
End Using
End Using
I have had to guess at your data types, but it should be fairly clear how to switch between different types. It is also about 5 years since I wrote anything in VB.NET so please forgive any syntax errors.

Related

MS Access running SQL Stored Procedure Write Issue

I have managed to build a Access VBA query that runs a SQL Stored Procedure with parameters and seems to run and complete without incidence, however it does not write the data into the SQL Database. Am I missing a curtail part of coding?
The data is gathered from a form.
Function AddStaff()
Dim adoCN As New ADODB.Connection
Dim sConnString As String
Dim cmdObjCMD As New ADODB.Command
Dim BrandDataTxt
Dim StaffNameDataTxt
Dim NTloginIDDataTxt
Dim NMCUsernameDataTxt
Dim StaffAuditLevelDataTxt
Dim EmailAddressDataTxt
Dim PhoneLoginDataTxt
Dim TeamNameDataTxt
Dim TeamSegmentDataTxt
Dim StartDateDataTxt
Dim JobTitleDataTxt
DoCmd.OpenForm "AddNewStaff"
Forms!AddNewStaff.TBoxBrand.Value = BrandDataTxt
Forms!AddNewStaff.TBoxStaffName.Value = StaffNameDataTxt
Forms!AddNewStaff.TBoxPCLoginID.Value = NTloginIDDataTxt
Forms!AddNewStaff.TBoxNMCUsername.Value = NMCUsernameDataTxt
Forms!AddNewStaff.TBoxStaffAuditLevel.Value = CVar(StaffAuditLevelDataTxt)
Forms!AddNewStaff.TBoxEmailAddress.Value = EmailAddressDataTxt
Forms!AddNewStaff.TBoxPhoneLogin.Value = PhoneLoginDataTxt
Forms!AddNewStaff.TBoxTeamName.Value = TeamNameDataTxt
Forms!AddNewStaff.TBoxTeamSegment.Value = TeamSegmentDataTxt
Forms!AddNewStaff.TBoxStartDate.Value = CDate(StartDateDataTxt)
Forms!AddNewStaff.TBoxJobTitle.Value = JobTitleDataTxt
Set adoCN = New ADODB.Connection
sConnString = "Provider = SQLOLEDB; " & _
"Data Source = KCOMSQL26; " & _
"Initial Catalog = EclipseDW; " & _
"User ID = EclipseDW; " & _
"Password = M1Reporting; " & _
"Trusted_Connection = Yes; "
adoCN.Open sConnString
With cmdObjCMD
.ActiveConnection = sConnString
.CommandType = adCmdStoredProc
.CommandTimeout = 180
.CommandText = "Staff.usp_AddNewStaffMember"
.NamedParameters = True
.Parameters("#Brand") = " '" & BrandDataTxt & "'"
.Parameters("#StaffPrefName") = " '" & StaffNameDataTxt & "'"
.Parameters("#NTLoginID") = " '" & NTloginIDDataTxt & "'"
.Parameters("#NMCUsername") = " '" & NMCUsernameDataTxt & "'"
.Parameters("#StaffAuditLevel") = " " & StaffAuditLevelDataTxt & ""
.Parameters("#EmailAddress") = " '" & EmailAddressDataTxt & "'"
.Parameters("#PhoneLogin") = " '" & PhoneLoginDataTxt & "'"
.Parameters("#TeamName") = " '" & TeamNameDataTxt & "'"
.Parameters("#TeamSegment") = " '" & TeamSegmentDataTxt & "'"
.Parameters("#StartDate") = " " & StartDateDataTxt & ""
.Parameters("#JobTitle") = " '" & JobTitleDataTxt & "'"
.Execute
End With
adoCN.Close
End Function
SQL Code
EXEC staff.usp_AddNewStaffMember
#Brand = 'CSO North'
, #StaffPrefName = 'Test Agent'
, #NTLoginID = 'TestAgent'
, #NMCUsername = 'TestAgent'
, #StaffAuditLevel = '1'
, #EmailAddress = 'TestAgent#kcom.com'
, #PhoneLogin = '99999'
, #TeamName = 'Customer Services'
, #TeamSegment = 'Customer Services'
, #StartDate = '2017-04-18'
, #JobTitle = 'Test Agent'

VBS Script that shows the files created on a specific date

I want to create a script that shows the files created on a specific date in a specific location.
As for now I created this:
Set objWMIService = GetObject("winmgmts:" & "!\\" & "." & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile where Drive='C:' AND Path='\\' AND CreationDate Like '20071107%' ")
For Each objFile in colFiles
Buffer = Buffer & objFile.FileName & " - " & objFile.CreationDate & vbNewLine
Next
Wscript.echo Buffer
But I am getting error in this line: " AND CreationDate Like '20071107%' "
So it does not work in such a way as I thought it will be - in C:\ I have a lot eula.txt files created on 2007 11 07.
I do not ask about finished code, but only for a clue. Thanks!
WHERE clause of a WQL query defends or inhibits from using wildcards in CIM_DATETIME values. Use SWbemDateTime object as follows:
option explicit
On Error GoTo 0
Dim strResult: strResult = Wscript.ScriptName
Dim objWMIService, colFiles, objFile, dTargetDate, dMinDate, dMaxDate, dateTime
Set dateTime = CreateObject("WbemScripting.SWbemDateTime")
dTargetDate = #2007-11-07# ' date literal in yyyy-mm-dd format
dateTime.SetVarDate( dTargetDate) ' convert to CIM_DATETIME
dMinDate = datetime
dateTime.SetVarDate( DateAdd( "d", 1, dTargetDate))
dMaxDate = datetime
strResult = strResult & vbNewLine & dMaxDate
Set objWMIService = GetObject("winmgmts:" & "!\\" & "." & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery ( _
"Select * from CIM_DataFile where Drive='c:' AND Path='\\'" _
& " AND CreationDate >= '" & dMinDate & "'" _
& " AND CreationDate < '" & dMaxDate & "'" _
)
If colFiles.Count = 0 Then
strResult = strResult & vbNewLine & "no files found"
Else
For Each objFile in colFiles
strResult = strResult & vbNewLine & objFile.FileName & " " & objFile.Extension _
& " - " & objFile.CreationDate
Next
End If
Wscript.Echo strResult
Wscript.Quit

VBA Access Compile Error - Data Member Not Found - How to ignore?

I have the code below in a button in my forms in MS Access. The problem is that sometimes not all "strCTRL"s exist. In some forms they do, in some they don't. The whole code is 900+ lines long so I won't post all of it. It's a SQL query which references controls and extracts their value.
The problem comes when not all controls are present, then I get the error: Compile error: Method or data Member not found.
Is there a way to bypass the compile error or tell VBA to compile it only if it exists? I tried If...Nothing and On Error Resume Next, but they don't seem to work. There's also other objects that will not exist on each page, not just the ones below. So...any ideas? =/
Dim strCTRL1 As String
Dim strCTRL2 As String
Dim strCTRL3 As String
Dim strCTRL4 As String
Dim strCTRL5 As String
Dim strCTRL6 As String
Dim strCTRL7 As String
Dim strCTRL8 As String
Dim strCTRL9 As String
Dim strCTRL10 As String
DoCmd.SetWarnings False
On Error Resume Next
strCTRL1 = "[Control Number] = " & Me.Text684.DefaultValue & " "
strCTRL2 = "[Control Number] = " & Me.Label2210.DefaultValue & " "
strCTRL3 = "[Control Number] = " & Me.Label2295.DefaultValue & " "
strCTRL4 = "[Control Number] = " & Me.Label73.DefaultValue & " "
strCTRL5 = "[Control Number] = " & Me.Label160.DefaultValue & " "
strCTRL6 = "[Control Number] = " & Me.Label246.DefaultValue & " "
strCTRL7 = "[Control Number] = " & Me.Label332.DefaultValue & " "
strCTRL8 = "[Control Number] = " & Me.Label417.DefaultValue & " "
strCTRL9 = "[Control Number] = " & Me.Label506.DefaultValue & " "
strCTRL10 = "[Control Number] = " & Me.Text2285.DefaultValue & " "
You can create an array or list of the label names, then:
Dim LabelName As String
Dim LabelNames As Variant
LabelNames = Array("Text684", "Label2210", ...etc.)
' ...
LabelName = LabelNames(1)
strCTRL1 = "[Control Number] = " & Me(LabelName).DefaultValue & " "
That will compile, though - of course - fail at runtime for non-existing labels.
OK, thanks to #Gustav, you got your code to compile, and his suggestions, combined with On Error Resume Next will get your code to run without errors under any circumstance.
But there is no way to tell if your code is correct, because now, the compiler won't tell you which controls are misnamed or missing.
So instead, I would suggest an array-based approach like this:
Dim Ctl As Access.Control
Dim CtlValues() As String
Dim i as Long
i = 0
ReDim CtlValues 1 To Me.Controls.Count
For Each Ctl In Me.Controls
If Ctl.ControlType = acTextBox Then
i = i + 1
CtlValues(i) = "[Control Number] = " & CStr(Nz(Ctl.DefaultValue, "Null"))
End If
Next
ReDim Preserve CtlValues 1 To i
These 12 lines of code perform the same task that the 900 lines do (going by your example). This code will work in any form, regardless of how many controls there are, and what they are named. This code is way easier to understand and work with.
See if maybe an approach like this will work here.

Using FTSearch with date fields

I have code that will search particular fields in the document to find the values that the user selects and places those documents in a folder. I have the code working, but I'm stuck on how to proceed with doing the same thing with date fields. I need to be able to find documents within a date range. Can anyone help me with how to go about doing this? Here is the code that I have:
Sub Initialize
On Error GoTo ErrHandler
Dim ws As New NotesUIWorkspace
Dim session As New NotesSession
Dim db As NotesDatabase
Dim RemoveView As NotesView
Dim RemoveDoc As NotesDocument
Dim RemoveEntry As NotesViewEntryCollection
Dim dc As NotesDocumentCollection
Dim doc As NotesDocument
Dim view As NotesView
Dim j As Integer
Dim DialogDoc As NotesDocument
Set db = session.CurrentDatabase
Folder$ = "(UseOfForceSearch)"
'Clear folder before inputting current search results.
Set RemoveView = db.GetView(Folder$)
Set RemoveDoc = RemoveView.GetFirstDocument
If Not (RemoveDoc Is Nothing) Then
Set RemoveEntry = RemoveView.AllEntries
Call RemoveEntry.RemoveAllFromFolder(Folder$)
End If
If Not (db.IsFTIndexed) Then
answer = MessageBox(" Sorry. This database is not full-text indexed." + "Do you want to create an index?", MB_YESNO)
If (answer = IDYES) Then
Call db.UpdateFTIndex(True)
End If
End If
Set DialogDoc = db.Createdocument
searchForm$ = "$Force"
Form$ = "ReportDialog" 'Ask user for specifics of search using ReportDialog
Title$ = "Use of Force Search Criteria"
DialogDoc.Form = Form$
DialogDoc.StartDate = DialogDoc.StartDate(0)
DialogDoc.EndDate = DialogDoc.EndDate(0)
DialogDoc.Field1 = DialogDoc.Field1(0)
DialogDoc.Value1 = DialogDoc.Value1(0)
DialogDoc.Field2 = DialogDoc.Field2(0)
DialogDoc.Value2 = DialogDoc.Value2(0)
DialogDoc.Field3 = DialogDoc.Field3(0)
DialogDoc.Value3 = DialogDoc.Value3(0)
DialogDoc.Field4 = DialogDoc.Field4(0)
DialogDoc.Value4 = DialogDoc.Value4(0)
DialogDoc.Field5 = DialogDoc.Field5(0)
DialogDoc.Value5 = DialogDoc.Value5(0)
DialogDoc.Logic1 = DialogDoc.Logic1(0)
EnterDialog:
If (ws.DialogBox(Form$, True, True, False, True, False, False, Title$,DialogDoc,True)) Then
Else
Exit Sub
End If
SDate$ = CStr(DialogDoc.StartDate(0))
EDate$ = CStr(DialogDoc.EndDate(0))
Field1$ = UCase(CStr(DialogDoc.Field1(0)))
Field2$ = UCase(CStr(DialogDoc.Field2(0)))
Field3$ = UCase(CStr(DialogDoc.Field3(0)))
Field4$ = UCase(CStr(DialogDoc.Field4(0)))
Field5$ = UCase(CStr(DialogDoc.Field5(0)))
Oper$ = "contains"
Value1$ = UCase(CStr(DialogDoc.Value1(0)))
Value2$ = UCase(CStr(DialogDoc.Value2(0)))
Value3$ = UCase(CStr(DialogDoc.Value3(0)))
Value4$ = UCase(CStr(DialogDoc.Value4(0)))
Value5$ = UCase(CStr(DialogDoc.Value5(0)))
Logic1$ = UCase(CStr(DialogDoc.Logic1(0)))
Logic2$ = UCase(CStr(DialogDoc.Logic2(0)))
Logic3$ = UCase(CStr(DialogDoc.Logic3(0)))
Logic4$ = UCase(CStr(DialogDoc.Logic4(0)))
Set Date1 = New NotesDateTime(SDate$)
Set Date2 = New NotesDateTime(EDate$)
Date1ForReport$ = Date1.DateOnly
Date2ForReport$ = Date2.DateOnly
datemax = Date2.timedifference(Date1)
DaysBetween = datemax \ 86400
If(DaysBetween > (366 * 1)) Then
MessageBox "Date range cannot exceed 1 year.",48,"Error:"
GoTo EnterDialog
End If
For i = 1 To 1
searchForm$ = "(FIELD Form contains $Force) and "
Expr1$ = "FIELD " + Field1$ + " " + Oper$ + " " + Value1$
Expr2$ = "FIELD " + Field2$ + " " + Oper$ + " " + Value2$
Expr3$ = "FIELD " + Field3$ + " " + Oper$ + " " + Value3$
Expr4$ = "FIELD " + Field4$ + " " + Oper$ + " " + Value4$
Expr5$ = "FIELD " + Field5$ + " " + Oper$ + " " + Value5$
FinalExpr$ = searchForm$ + Expr1$
If(Logic1$ <> "") Then
FinalExpr$ = FinalExpr$ + " " + Logic1$ + " " + Expr2$
ElseIf (Logic2$ <> "") Then
FinalExpr$ = FinalExpr$ + " " + Logic1$ + " " + Expr2$ + " " + Logic2$ + " " + Expr3$
ElseIf (Logic3$ <> "") Then
FinalExpr$ = FinalExpr$ + " " + Logic1$ + " " + Expr2$ + " " + Logic2$ + " " + Expr3$ + " " + Logic3$ + " " + Expr4$
ElseIf (Logic4$ <> "") Then
FinalExpr$ = FinalExpr$ + " " + Logic1$ + " " + Expr2$ + " " + Logic2$ + " " + Expr3$ + " " + Logic3$ + " " + Expr4$ + " " + Logic4$ + " " + Expr5$
End If
FinalExpr$ = FinalExpr$
Print "Searching..."
' the number 16384 means fuzzy search
Set dc = db.FTSearch(FinalExpr$,0,,16384)
Folder$ = "(UseOfForceSearch)"
Call dc.PutAllInFolder(Folder$,True)
Next
Print "Search Completed with " + CStr(dc.Count) + " results."
Set view = db.getView(Folder$)
Exit Sub
ErrHandler:
MessageBox "Error" & Str(Err) & ": " & Error$,16,"Error!"
Exit Sub
End Sub
You can use operators = / < / > / <= / >= for date fields in FTSearch.
Example: FIELD YourDateField > 01/30/2013 or [YourDateField] > 01/30/2013.
To find documents within a date range you'd write:
[YourDateField] >= 01/01/2013 AND [YourDateField] <= 12/31/2013
Look here for a complete list of search options.

libpq, insert with parameters

I am wondering if I can make parameterized queries directly from C/C++ with libpq instead of using strings and if do how should this code look's like?
string tblins = "";
tblins = "INSERT INTO " + commtable + " "
"(vdoc, bdoc, mytime, txml) VALUES ("
"'" + cxml.vdoc + "', "
+ cxml.bdoc + ", " //integer
"'" + cxml.mytime + "', "
"'" + cxml.txml + "')";
result = PQexec(conn, tblins.c_str());
Thanks.
Yes, you can use the PQexecParams function as explained in the documentation.
If parameters are used, they are referred to in the command string as $1, $2, etc. nParams is the number of parameters supplied; it is the length of the arrays paramTypes[], paramValues[], paramLengths[], and paramFormats[].