SQL Syntax to Insert Dates and Times into a Database - sql

In my project, I need to convert the following function, which creates a string to insert into a database, into the correct syntax for inserting a datetime datatype... Does anyone know a way I can do this?
Public Shared Function sqlString(str As String) As String
Return "'" & str.Replace("'", "''") & "'"
End Function

sql = "INSERT INTO tblModules(ModuleID, ModuleName, NumberUsers, License, Username, ContractID,datetime) VALUES(" & modID & ", " & sqlString(modname) & ", " & numusers & "," & sqlString(license) & ", " & sqlString(username) & ", " & contractID & ","&sqlDateTime(DateTime.Now)&")"
try this

In the end, I stored the values as either a date or a time by calling the following functions respectively, during the INSERT statement
Public Shared Function sqlDate(dt As DateTime) As String
If dt.Date = Nothing Then
Return dt.ToString("")
Else
Return dt.ToString("yyyy-MM-dd")
End If
End Function
Public Shared Function sqlTime(dt As DateTime) As String
Return dt.ToString("hhmmss")
End Function

Related

VBA bad syntax in dlookup function with global variables

I am using 8 similar functions in my code and they all work, but this one is not working:
global_var_13=DLookup("[amount]", "[tabla amortizacion real]","[no contract]= get_global('global_var_10') and [ident]=get_global('global_var_11') and [cuota]= get_global('global_var_12')")
var_10 is a string, var_11, var_12, and var_13 are numeric.
The values are var_10= "GAF-27/2013", var_11=1, var_12=1
global_var_13 is returning NULL
Any thoughts about the syntax?
Try to concatenate the clause elements:
global_var_13 = DLookup("[amount]", "[tabla amortizacion real]", "[no contract] = '" & get_global("global_var_10") & "' and [ident] = " & get_global("global_var_11") & " and [cuota] = " & get_global("global_var_12") & "")

date + time from vb6 to SQL

I have this code in VB6
Dim datahorS As String
datahorS = Text21.text & " " & Text22.text
Label2.Caption = datahorS
SQL = " insert into TabNFe_x ( data_hora_ent) values " _
& "(" & "'" & datahorS & "'" & ")"
datahorS = 20/10/2016 13:54
and the command
insert into TabNFe_x ( data_hora_ent) values ('20/10/2016 13:54')
erro from SQL
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
what's i m making wrong.
Convert your string into a datetime
Select convert(datetime, '20/10/2016 13:54', 103)
Returns
2016-10-20 13:54:00.000

ExecuteNonQuery() won't work for INSERT function

First of all, I'm not a professional programmer. So there are some big faults possible in my program!
The problem is:
I linked my WPF file in visual express with a MS Access database (format 2003). Whenever I try to run the following (sorry for the dutch code):
Public Sub ToevoegenPersoon(voornaam As String, achternaam As String, mailadres As String, geboortedatum As Date, klantennummer As Integer, specialeCategorie As String)
Dim opdracht As OleDbCommand
Dim sqlOpdracht As String
sqlOpdracht = "INSERT INTO Klant (Voornaam, achternaam, mailadres, geboortedatum, klantennummer, specialeCategorie)" & _
"VALUES (" & Chr(34) & "" & voornaam & "" & Chr(34) & "," & Chr(34) & "" & achternaam & "" & Chr(34) & "," & Chr(34) & "" & _
mailadres & "" & Chr(34) & "," & Convert.ToString(geboortedatum) & "," & Convert.ToString(klantennummer) & "," & Chr(34) & "" & specialeCategorie & "" & Chr(34) & ")"
opdracht = New OleDbCommand(sqlOpdracht, connectie)
Debug.WriteLine(sqlOpdracht)
MsgBox(sqlOpdracht)
opdracht.Connection.Open()
opdracht.ExecuteNonQuery()
opdracht.Connection.Close()
End Sub
my program always has an error for the ExecuteNonQuery() function. This function is used for the following event:
Private Sub btnKlantToevoegen_Click(sender As Object, e As RoutedEventArgs) Handles btnKlantToevoegen.Click
Dim achternaam As String = boxVoornaam.Text
Dim voornaam As String = boxAchternaam.Text
Dim emailadres As String = boxEmailadres.Text
Dim geboortedatum As Date = GeboortedatumSelectie.SelectedDate
Dim klantennummer As Integer = 5
Dim specialeCategorie As String = "Jeugd"
Try
database.ToevoegenPersoon(voornaam, achternaam, emailadres, geboortedatum, klantennummer, specialeCategorie)
Catch ex As Exception
End Try
boxAchternaam.Clear()
boxVoornaam.Clear()
boxEmailadres.Clear()
End Sub
At the top, I stated the following to connect MS Access database with Visual express:
Private connectiestring As String = My.Settings.Database_Drijkoningen_Konings1ConnectionString
Private connectie As OleDbConnection
connectie = New OleDbConnection(connectiestring)
When running this program, the executenonquery() gives an error. And I have no clue whatsoever what it can be. Anybody who does?
Thanks in advance
Jeroen
Not sure if this could resolve your problem. I don't know the error message. However I will show a simple parameterized query that probably could help a lot
Public Sub ToevoegenPersoon(voornaam As String, achternaam As String, mailadres As String, geboortedatum As Date, klantennummer As Integer, specialeCategorie As String)
Dim opdracht As OleDbCommand
Dim sqlOpdracht As String
sqlOpdracht = "INSERT INTO Klant (Voornaam, achternaam, mailadres, " & _
"geboortedatum, klantennummer, specialeCategorie) " & _
"VALUES (?,?,?,?,?,?)"
opdracht = New OleDbCommand(sqlOpdracht, connectie)
opdracht.Parameters.AddWithValue("#p1", voornaam)
opdracht.Parameters.AddWithValue("#p2", achternaam)
opdracht.Parameters.AddWithValue("#p3", mailadres)
opdracht.Parameters.AddWithValue("#p4", Convert.ToString(geboortedatum))
opdracht.Parameters.AddWithValue("#p5", Convert.ToString(klantennummer))
opdracht.Parameters.AddWithValue("#p6", specialeCategorie)
opdracht.Connection.Open()
opdracht.ExecuteNonQuery()
opdracht.Connection.Close()
End Sub
Now, with a parameterized query there is no more concatenations on the command text and this alone will remove any possibility to forget some quote or comma between value. (Of course this removes also the Sql Injection problem and the parsing of strings that contain special characters)
There is still a problem to be resolved. The 4th and 5th parameter receive a string value. This requires the underlying field on the datatable to be a string field and not a DateTime. If this is not the case then you need to pass (as parameter value) just the date value

insert date and time into acces with SQL visual basic

I am trying to use SQL in visual basic to insert Date and Time value into Access 2007 running in Access2002/3 mode. Using my code I have managed to insert text strings and numerical values into the table. However for the DateTime field get a syntax error. The field in Access is set as a Date/Time field type.
Below is my first function which generates the queries for the Database Accessing function:
Public Function NewUpload(ByVal UploadType As String) As Single
Dim UploadNumber As Single
Dim ColumnString As String
Dim ValueString As String
If DatabaseConnection("SELECT ID_UPL FROM tabUpload", "Read Recordset") = "Error" Then GoTo close
Do Until rdrOLEDB.Read = False
If Val(rdrOLEDB.Item(0).ToString()) > UploadNumber Then UploadNumber = Val(rdrOLEDB.Item(0).ToString())
Loop
rdrOLEDB.Close()
cnnOLEDB.Close()
UploadNumber = UploadNumber + 1
'Update Uploads table:
ColumnString = "ID_UPL,DateTime,IDUser,DataCalc"
ValueString = Format(UploadNumber, "0000") & ",#" & Now.ToLongDateString & " " & Now.ToLongTimeString & "#,'" & My.User.Name & "','" & UploadType & "'"
If DatabaseConnection("INSERT INTO tabUpload(" & ColumnString & ") VALUES(" & ValueString & ")", "Non-Query") = "Error" Then GoTo Close
NewUpload = UploadNumber
Close:
cnnOLEDB.Close()
End Function
Here is the second Function which connects to the Database
Public Function DatabaseConnection(ByVal Query As String, ByVal Task As String) As String
'On Error GoTo Err
cnnOLEDB.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DataDirectoryName & DatabaseFileName
cmdOLEDB.Connection = cnnOLEDB
cmdOLEDB.CommandText = Query
cnnOLEDB.Open()
Select Case Task
Case "Read Recordset"
rdrOLEDB = cmdOLEDB.ExecuteReader()
DatabaseConnection = "Read Recordset"
Case "Read Scalar"
DatabaseConnection = Str(cmdOLEDB.ExecuteScalar)
Case "Non-Query"
DatabaseConnection = Str(cmdOLEDB.ExecuteNonQuery())
DatabaseConnection = "Non-Query"
End Select
Exit Function
Err:
MsgBox("Database connection error.")
DatabaseConnection = "Error"
End Function
When I run this code I get the Query:
INSERT INTO tabUpload(IDUPL, DateTime, User, DataCalc) VALUES(0003, #17 August 2012 14:23:27#, 'UK\Pej', 'Calc')"
I have also tried several variations of DateTime using format and now(Year) giving yyyy-mm-dd etc.
Any help would be greatly appreciated.
Both datetime and user are reserved words and must be enclosed in square brackets. Otherwise, it will run with that date.
INSERT INTO tabUpload(IDUPL, [DateTime], [User], DataCalc)
VALUES(0003, #17 August 2012 14:23:27#, 'UK\Pej', 'Calc')"
You're taking Vb.Net Now and making a literal value from it, then inserting that literal into your Date/Time field. However, the Access db engine provides its own Now() function, so you can use that function in your INSERT statement.
INSERT INTO tabUpload (IDUPL, [DateTime], [User], DataCalc)
VALUES(3, Now(), 'UK\Pej', 'Calc')
Try to insert the date in the ODBC canonical format:
Format (Date, "yyyy-mm-ddThh:nn:ss")
Here's the documentation for the format function.

SQL command will not insert into database

I'm trying to use a VB button to insert data into a database, but it keeps bringing up the error message I have in place for exceptions.
Can anyone help me with why this does not update the database?
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sql As String
Dim adapter As New SqlDataAdapter
Dim Customer As String = TextBox1.Text
Dim Product As String = TextBox2.Text
Dim Location As String = TextBox3.Text
Dim Details As String = TextBox4.Text
Dim Owners As String = DropDownList1.Text
Dim Urgency As String = DropDownList2.Text
connetionString = "Data Source=ZUK55APP02;Initial Catalog=BugFixPortal;User ID=SLC***;Password=rep***"
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details) VALUES ('" & Owners & ", " & Customer & ", " & Product & ", " & Location & ", " & Urgency & ", " & Details & "')"
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
adapter.UpdateCommand = sqlCnn.CreateCommand
adapter.UpdateCommand.CommandText = sql
adapter.UpdateCommand.ExecuteNonQuery()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
End Try
End Sub
I would not go down this road as your code is weak against SQL Injection
you should use parameters instead.Something like the below
c.Open();
string insertString = #"insert into YourTable(name, street, city,....) values(#par1, #par2, #parN,....)"
SqlCommand cmd = new SqlCeCommand(insertString, c);
cmd.Parameters.Add("#par1", SqlDbType.VarChar).Value = "MyName";
//etc
cmd.ExecuteNonQuery();
c.Close();
You are incorrectly quoting your values.
This string has an opening and closing single quote around ALL the values, which is incorrect.
VALUES ('" & Owners & ", " & Customer & ", " & Product & ", " & Location & ", " & Urgency & ", " & Details & "')"
Instead, put single quotes around character data, eg., if Product is a varchar, it would look like this:
VALUES (" & Owners & ", " & Customer & ", '" & Product & "', " & Location & ", " & Urgency & ", " & Details & ")"
The real problem, though, is that you should be using parameterized queries instead. This code is prone to SQL injection attacks.
Change this;
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
to Something like this;
MsgBox("Unable to update Database with Request - Please speak to Supervisor!" & ex.Message)
It will give you more details on the exception, however at a quick glance I can see a problem, the values you are trying to insert are strings, you've enclosed all your values in a single set of ' characters, rather than enclosing each string parameter in a pair of ' values, i.e.
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details) VALUES ('" & Owners & "', '" & Customer & "', '" & Product & "',' " & Location & "', '" & Urgency & "', '" & Details & "')"
You really should look at parameterizing your queries as you're wide open to SQL injection attacks. See HERE
In terms of your code itself, your SQL syntax is wrong as you need to put apostrophes around each value. Try this:
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details)
VALUES ('" & Owners & "', '" & Customer & "', '" & Product &
"', '" & Location & "', '" & Urgency & "', '" & Details & "')"
Here's an example using Parameters
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details)
VALUES ('#Owners', '#Customer', '#Product', '#Location', '#Urgency', '#Details')"
Then add parameters like so:
command.Parameters.AddWithValue("#Owners", Owners)
command.Parameters.AddWithValue("#Customer", Customer)
command.Parameters.AddWithValue("#Product", Product)
command.Parameters.AddWithValue("#Location", Location)
command.Parameters.AddWithValue("#Urgency", Urgency)
command.Parameters.AddWithValue("#Details", Details)
I think you want to use adapter.InsertCommand instead of adapter.UpdateCommand
in
Try
sqlCnn.Open()
adapter.UpdateCommand = sqlCnn.CreateCommand //(adapter.InsertCommand)
adapter.UpdateCommand.CommandText = sql //(adapter.InsertCommand)
adapter.UpdateCommand.ExecuteNonQuery() //(adapter.InsertCommand)
sqlCnn.Close()
Catch ex As Exception
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
End Try
and agree with parametrized sql query
see http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx for more infos