I am created a journal program for an internship project and I am using a MS-Access Database. I am programming in VB.net. Now, I am trying to make it so that they can "Update" their journals, meaning that they click on their calendar date and it brings them to that journal if they have one for that date. If they have one for that date then it shows the title and journal text entry for that date. I want to make it so that any changes they have made to the journal (editing the textbox fields) are also changed in the database when they click the update button. Here's what i have so far
Private Sub COE_JournalBtn_Click(sender As System.Object, e As System.EventArgs) Handles COE_JournalBtn.Click
If DateTimePicker1.Value <> Nothing Then
If TitleTxt.Text <> "" Then
If JournalTextRtxt.Text <> "" Then
myConnection.Open()
Dim DatePicked As String = DateTimePicker1.Value
Dim cmd As OleDbCommand
Dim str As String
Try
MyJournalTitle = TitleTxt.Text
MyJournalText = JournalTextRtxt.Text
str = "UPDATE Journals SET JournalTitle='" & MyJournalTitle & "', JournalText='" & MyJournalText & "' WHERE JournalDate=" & DatePicked
cmd = New OleDbCommand(str, myConnection)
cmd.ExecuteNonQuery()
myConnection.Close()
Catch ex As Exception
MessageBox.Show("There was an error processing your request. Please try again." & vbCrLf & vbCrLf & _
"Original Error:" & vbCrLf & vbCrLf & ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
myConnection.Close()
End Try
myConnection.Close()
End If
End If
End If
End Sub
Now my update string by itself is
"UPDATE Journals SET JournalTitle='" & MyJournalTitle & "', JournalText='" & MyJournalText & "' WHERE JournalDate=" & DatePicked
Now, what happens, is absolutely nothing. No errorboxes come up. No messageboxes appear. The program doesn't freeze. And the database remains unchanged. What am I doing wrong? Is there an error in my code or something missing? Please help me because I really want to figure this out and i've been looking everywhere for a solution in VB.net and cannot find one that applies to me being that I am using MS-Access and NOT SQL.
Thanks in advance,
Richard Paulicelli
Use a parametrized query to avoid Sql Injection Attacks and quoting problems
str = "Journals SET JournalTitle=?, JournalText=? WHERE JournalDate=?"
cmd = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("#jounalTitle", MyJournalTitle )
cmd.Parameters.AddWithValue("#journalText", MyJournalText)
cmd.Parameters.AddWithValue("#journalDate", DatePicked)
cmd.ExecuteNonQuery()
Using parameters will free your code from that continue quoting that expose your code to an high chance of typing errors. And you don't have any problem with Sql Injection
You may have a problem with this part of your UPDATE statement:
"' WHERE JournalDate=" & DatePicked
If the Journals field, JournalDate, is Date/Time data type, surround the date string value with Access date delimiter characters (#).
"' WHERE JournalDate=#" & DatePicked & "#"
You can also convert your date string to yyyy-mm-dd format to avoid misinterpreting the date literal based on local.
I agree with the suggestions to use a parameter query for this instead. I'm just trying to help you understand why the original attempt may have failed.
Related
I see there are a lot of questions on this issue, but I thought I'd add to it again. I'm trying to run Pass Through queries to put the load on the server instead of wimpy Access. Almost every table I have is stored in a SQL server, but I have a large table I have to loop through and it's much faster if I copy it to a local table and then loop through it. Otherwise, everything is faster or fast enough when going through the pass through functions.
The table in question currently holds about 25k lines and if I just write a query to have access copy the local table to SQL server it takes about 1 hour. However, if I use a pass through query with insert, I can copy it over in about 47 seconds. My problem seems to come when I try to pass too long of a string of text.
Here is my function that run the pass through query
Public Sub RunPassThruQdf(sqlCode As String, Optional isTestDB As Boolean = False)
Dim qdf As QueryDef
Set qdf = CurrentDb.QueryDefs("vbaSQL")
If isTestDB Then
qdf.Connect = "ODBC;DSN=DataWarehouse_Test;Description=DataWarehouse_Test;UID=**username**;PWD=**password**;APP=Microsoft Office;DATABASE=DataWarehouse_test"
'The above line is where the error happens when I debug
Else
qdf.Connect = "ODBC;DSN=DataWarehouse;Description=DataWarehouse;UID=**username**;PWD=**password**;APP=Microsoft Office;DATABASE=DataWarehouse"
End If
qdf.ReturnsRecords = False
qdf.sql = sqlCode
Do Until InStr(qdf.sql, " ") = 0
qdf.sql = Replace(qdf.sql, " ", " ")
Loop
qdf.Execute
qdf.Close
End Sub
You'll notice that it connects with a special login (redacted) because I can't make changes to the server myself, but that user account can. And that last loop removes double spaces until everything is separated by a single space to reduce the string size as much as possible.
And this is the function that copies the local table to the server table
Public Sub LoadUnidentifiedFromLocal()
Dim rst As New RecordsetClass: rst.OpenR "tblUnidentifiedParts_Local"
Dim dtm As Date: dtm = Now
Dim baseSQL As String: baseSQL = "INSERT INTO [DataWarehouse_test].[dbo].[mT_SalesAttributeDB_UnidentifiedParts] (ID, PartNumber, FamilyNumber, AutoNote, ManualNote, Created, Updated) VALUES "
Dim sql As String
RunPassThruQdf "SET IDENTITY_INSERT [DataWarehouse_test].[dbo].[mT_SalesAttributeDB_UnidentifiedParts] ON", True
Dim i As Integer: i = 1
Do Until rst.EOF
If sql = vbNullString Then sql = baseSQL
If i Mod 500 = 0 Then
RunPassThruQdf sql, True
'Debug.Print i & ": " & Format(Now - dtm, "hh:mm:ss") & " (" & Format(Len(sql), "#,##0") & ")"
'DoEvents
sql = baseSQL
End If
Dim addSQL As String: addSQL = "(" & rst.Fields("ID") & ", '" & rst.Fields("PartNumber") & "', '" & rst.Fields("FamilyNumber") & "', '" & rst.Fields("AutoNote") & "', '" & rst.Fields("ManualNote") & "', '" & rst.Fields("Created") & "', '" & rst.Fields("Updated") & "')"
If sql = baseSQL Then
sql = sql & addSQL
Else
sql = sql & ", " & addSQL
End If
rst.MoveNext
i = i + 1
Loop
If sql <> vbNullString Then
RunPassThruQdf sql, True
Debug.Print i & " " & Format(Now - dtm, "hh:mm:ss")
End If
RunPassThruQdf "SET IDENTITY_INSERT [DataWarehouse_test].[dbo].[mT_SalesAttributeDB_UnidentifiedParts] OFF", True
rst.CloseR
End Sub
Where I have that mod 500 is me trying to figure out how many lines I can copy over until I get that System resources exceeded error. You'll probably also notice I have a special rst class I made. But just know that it mimics the normal one, I just have some special functions in there so it was my version of inheritance since VBA doesn't support that.
The first time I got it I googled and found that someone was able to fix their error by change the max lock to 1 million. And that worked for me too, until I exceeded it. DAO.DBEngine.SetOption dbMaxLocksPerFile, 1000000
I know it's not a problem with my computer, it's 6 core Xeon W-10855M with 64GB of ram. But I will see that error even after restart for a while and then it will just stop and work again until I try to send it too much and then I'm stuck seeing it for a bit. What is weird is even restarting my computer will not fix the issue. And I've tried compress and repair and that won't fix it either. So I'm not clear what changes so that it stops reporting that.
But my first question is if increasing the max locks per file helped, is there a way to clear what locks are currently there? My second question would be how big of a string can I send with a pass through, I think I saw somewhere in the neighborhood of 65k before I got the message (That was when I had it set at i mod 500.
I'm writing a VB.net program that records data in SQL Server 2012. At this stage I'm trying to create a new row in the database. The primary key automatically creates a line N+1, and to create the line you enter a new serial number. This all worked the other day, except you could not then load the row into the form to edit the rest of the data because it was tripping up on the nulls.
Anyway, I decided as I created the new row I'll load a blank space " " into all text boxes, today's date into all date boxes and a 'false' return on all check boxes. I've also added code to check for nulls. Below is the code to insert a result into the checkboxes, but I get an error
Incorrect syntax near '='
My code:
Private Sub btnAddNewSerial_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click, btnAddNewSerial.Click
Try
con.ConnectionString = (frmAdmin.lblDBConnection.Text & frmAdmin.txtDBPW.Text & frmAdmin.lblDBConnection2.Text)
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO SLE1000DB (SK2SoakMainPCB) " & _
"VALUES (#SK2SoakMainPCB)”
cmd.Parameters.AddWithValue("#SK2SoakMainPCB", SqlDbType.Bit).Value = FrmSLE1000.chkSoakInteruptionsMainPCB.Checked
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
con.Close()
MsgBox("Data updated")
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
Me.Hide()
frmSelect.Show()
End Sub
So if anyone can see whats causing the syntax error or can tell me a neater way of causing the checkbox to return a false result (I know that at the moment if it did work it would return a true result, that's something I'm still thinking about) Or just an overall neater way to achieve my goal that would be much appreciated. All my knowlage of VB.net and SQL Server comes from a book so is therefore, unfortunately, pretty limited!
The code presented here is just a snippet, there's actually an awful lot more columns that I'm passing data to, but I believe that its the checkboxes that are causing the syntax error as there aren't any "=" anywhere else in this bit of code and using a step through its this section that it gets caught up on.
Anyway thanks for your help!
Private Sub btnAddNewSerial_Click(sender As System.Object, e As
System.EventArgs) Handles btnAdd.Click, btnAddNewSerial.Click
Try
con.ConnectionString = (frmAdmin.lblDBConnection.Text &
frmAdmin.txtDBPW.Text & frmAdmin.lblDBConnection2.Text)
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO SLE1000DB (SK2SoakMainPCB) VALUES (#SK2SoakMainPCB)"
cmd.Parameters.AddWithValue("#SK2SoakMainPCB",FrmSLE1000.chkSoakInteruptionsMainPCB.Checked)
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
con.Close()
MsgBox("Data updated")
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
Me.Hide()
frmSelect.Show()
End Sub
the add parameter with value was incorrect. For more info : https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue(v=vs.110).aspx
hope this helps
I have a VBA script in MS Access that inserts a new record into a SQL Server table based on some inputs on the form.
Private Sub Allocate_Click()
Dim strSQL As String
strSQL = "INSERT INTO dbo_ALLOCATIONS " _
& "([Employee No],[Device Serial Number],[Start Date]) VALUES " _
& "('" & Me.EmployeeNumber & "', '" & Me.SerialNumber & "', '" & Me.StartDate & "')"
CurrentDb.Execute strSQL, dbFailOnError
Dim ReceiptNo As dao.Recordset
Set ReceiptNo = CurrentDb.OpenRecordset("select ##identity")
MsgBox "Device Successfully Allocated. Receipt ID is " & CurrentDb.OpenRecordset("select ##identity")
End Sub
At the end, I query the ID that was auto-incremented during the insert. I want to then quote this in a Message Box so the user can make use of it elsewhere. How can I get it to quote like that in the MsgBox command? The one I have at the moment causes lots of issues around the fact I can't combine this command, and when using only 'ReceiptNo' it says it's not a string.
There should only ever be a single result in the recordset. Try changing your last line to:
MsgBox "Device Successfully Allocated. Receipt ID is " & ReceiptNo(0)
It is not possible to print an entire recordset. You need to refer to the column that you want to print and loop through the recordset while the end of file is not reached. Then output your column as string. I did not test it though.
While not ReceiptNo.EOF
Msgbox Str(ReceiptNo!Identity)
ReceiptNo.moveNext
Wend
I have an SQL update command that I can't get to work. i want it to update the fields where the date is equal to the current date. It works for my INSERT and SELECT statements. But I get a missing operator error when using it for my Delete statement below.
Cmd.Connection = conn
Cmd.CommandText = "UPDATE tbl_Expenditure SET E_Stock =" & NewEStock & "," & "E_Total =" & ETotal & "WHERE [E_Date] = #" & thisMonth & "/" & Day & "/" & thisYear & "#;"
Cmd.ExecuteNonQuery()
Ive tried searching this site as well as others and can't seem to find an answer.
This is my error
Syntax error (missing operator) in query expression '95WHERE [E_Date] = #4/1/2015#'.
Thanks for any help
Using conn As New SqlConnection("connection string here"), _
cmd As New SqlCommand("UPDATE tbl_Expenditure SET E_Stock = #Stock, E_Total = #Total WHERE [E_Date] = #Date;", conn)
'Guessing at column types here
cmd.Parameters.Add("#Stock", SqlDbType.Int).Value = NewEStock
cmd.Parameters.Add("#Total", SqlDbType.Decimal, 8, 2).Value = ETotal
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = New DateTime(thisYear, thisMonth, Day)
cmd.ExecuteNonQuery()
End Using
This fixes a HUGE security issue in the code, it has a performance benefit in allowing Sql Server to cache your query plan, and it solves your problem in that is makes it much easier to spot silly syntax mistakes like the missing space in front of the WHERE clause.
I am using SQL 2005 as backend and MS Access as frontend.
Now, I get all my filtering of the data with views and no problems so far but I came accross some issues.
In access I had a form and on that form I had a field1 which I used to filter the data I wanted in that form with query. Example: Last, First Name or DOB. In Access I used the Expression builder to point the query to that field and I got my filter.
Now how do I do it in this new environment since when I create view (In Access) I can not filter on that field.
I was thinking on sp but I am not sure how do i go about it.
Any ideas?
I was thinking on sp but I am not sure how do i go about it.
If you still wanted to keep this form a normal “bound” access form then you could do something like this.
Setup a pass through query that fires your SP. The basic format for that is along the lines of this
EXEC [dbo].[spAgents_with_more_than_X_days_sick_by_Team] #Date_from = N'2009-09-14', #Date_to = N'2010-09-14', #Team_ID = N'TEM1', #Days_sick =5
You would then modify this when opening the form like this
Set qDef = DBEngine(0)(0).QueryDefs("RqryAgents_more_than_X_sicks_detail_2")
With qDef
.Connect = strSQL_con_string
.SQL = "EXEC [dbo].[spAgents_with_more_than_X_days_sick_by_Team]"
.SQL = .SQL & " #Date_from = N'" & Format(Me.txtDate_from, "yyyy-mm-dd") & "', "
.SQL = .SQL & "#Date_to = N'" & Format(Me.txtDate_to, "yyyy-mm-dd") & "', "
.SQL = .SQL & "#Team_ID = N'" & Me.txtTeam_ID & "', "
.SQL = .SQL & "#Days_sick =" & Me.txtDays_sick
End With
This should work just fine however if it was me (and I know it’s not everyone’s preference) but I would make this an unbound form and populate it by firing your SP using ADO to fill a recordset and go from there.
If you want details of how to do that then just ask and I will post an example
EDIT: Code sample added
Dim cmd as new ADODB.Command
Dim dbCon as new ADODB.Connection
Dim rst as new ADODB.Recordset
dbCon.ConnectionString=”Your_Connection_string”
dbCon.open
With cmd
.ActiveConnection = dbCon
.CommandText = "spYour SP"
.CommandType = adCmdStoredProc
.NamedParameters = True
.Parameters.Append .CreateParameter("#Your_pram1", adVarChar, adParamInput, 20, Format(Me.txtDate, "yyyy-mm-dd"))
.Parameters.Append .CreateParameter("#Your_pram2", adSmallInt, adParamInput, 0, Me.cboPhone_skill)
End With
Set rst = cmd.Execute()
With rst
If .EOF=False then
Me.txtYour_text_box_1=!Your_SP_field_1
Me.txtYour_text_box_2=!Your_SP_field_3
Me.txtYour_text_box_3=!Your_SP_field_2
End if
End with
Rst.close
Dbcon.close
Set rst=nothing
Set cmd=nothing
Set dbcon=nothing
You don't mention if these text boxes are in fact in the same form with the data and you don't mention if each text box was optional, and if they were not optional, then did you fill out 1, 2 or 3 boxes and then hit a button?
If you just looking to find people with a given lastName, then in the after update event of the un bound lastname box, just go:
Me.RecordSource = "select * from tblCustomers where LastName = '" & me.txtLastName "'"
The above is one line of code. I just don't see the need for so much code as others posted here.
You can expand on your question if you looking to make all 3 boxes optional, or if you looking to have a search based on more then one box, but I can rather tell you that you don't need the amounts of code posted here, but the one line of code as per above will suffice.