Insert into SQL table using VBA - sql-server

I have the table and fields created on the SQL end. The debugger points to the cnn.Execute uSQL being the issue. I am trying to write the user and computer name of who is accessing the sheet to SQL.
Sub UpdateTable()
Dim cnn As ADODB.Connection
Dim uSQL As String
Dim strText As String
Dim strDate As Date
Dim strUsername As String
Dim strComputerName As String
strUsername = Environ("username")
strComputerName = Environ("Computername")
Set cnn = New Connection
cnnstr = "Provider=SQLOLEDB; " & _
"Data Source=icl-analive; " & _
"Initial Catalog=DW_ALL;" & _
"User ID=dw_all_readonlyuser;" & _
"Trusted_Connection=Yes;"
cnn.Open cnnstr
uSQL = "INSERT INTO Audit (UN,CN) VALUES StrUsername , strComputer"
Debug.Print uSQL
cnn.Execute uSQL
cnn.Close
Set cnn = Nothing
Exit Sub
End Sub

Your uSQL should be like this:
uSQL = "INSERT INTO Audit (UN,CN) VALUES " & StrUsername & "," & strComputer
Edit:
Actually like this:
INSERT INTO Audit (UN,CN) VALUES '" & StrUsername & "','" & strComputer & "'"
The difference is that we should set the strings in inverted commas for the SQL. Thanks #Tony Dong in the comments.
This answer is a classic example of a vulnerable code for SQL injection.In order to prevent it, consider using parameterized queries as in this example:
VBA, ADO.Connection and query parameters

Related

Form Button will not run OpenRecordSet VBA

I am trying to use the following VBA code to run a select query in MS Access.
Private Sub ManuReport_Click()
Dim dbs As DAO.Database
Dim rsSQL As DAO.Recordset
Dim StrSQL As String
Set dbs = CurrentDb
strSQL = "SELECT " & _
"dbo_VENDOR1.ITEM_NO," & _
"dbo_VENDOR1.ITEM_PRICE," & _
"dbo_VENDOR2.ITEM_NO," & _
"dbo_VENDOR2.ITEM_PRICE," & _
"dbo_VENDOR1.MANUFACTURER_ITEM_NO," & _
"dbo_VENDOR1.MANUFACTURER," & _
"dbo_VENDOR1.ITEM_NAME " & _
"From dbo_VENDOR2 " & _
"INNER JOIN dbo_VENDOR1 " & _
"ON dbo_VENDOR2.MANUFACTURER_ITEM_NO = dbo_VENDOR1.MANUFACTURER_ITEM_NO " & _
"WHERE dbo_VENDOR1.MANUFACTURER IN ('MANUFACTURER CODE') " & _
"And dbo_VENDOR1.ITEM_PRICE > dbo_VENDOR2.ITEM_PRICE "
Set rsSQL = dbs.OpenRecordset(strSQL, dbOpenDynaset)
End Sub
I have added this to a button in MSACCES to pull this information from a linked SQL database. I have also been having issues with adding references to form text boxes but I may submit that as a separate question. Whenever I press the button, nothing happens. I don't even get an error screen. I have seen other answers where the issue seems to be how the OpenRecordSet is being used but I am having trouble understanding how I can apply it to this code.
The query itself does work when I create a separate query in Access so I am not sure where the problem is. I reformatted the SQL portion of the code to make it easier to read here, but I have it formatted as a single line in the actual VBA code.
It looks like you want to open a query in Access for display based on a SQL string
The following function will create a query based on the SQL string
Function createQry(qryName As String, sSQL As String)
Dim qdf As QueryDef
' Delete existing query
On Error Resume Next
CurrentDb.QueryDefs.Delete (qryName)
On Error GoTo 0
Set qdf = CurrentDb.CreateQueryDef(qryName, sSQL)
End Function
If you use this code in your posted code like that
Private Sub ManuReport_Click()
Dim dbs As DAO.Database
Dim rsSQL As DAO.Recordset
Dim StrSQL As String
Set dbs = CurrentDb
StrSQL = "SELECT " & _
"dbo_VENDOR1.ITEM_NO," & _
"dbo_VENDOR1.ITEM_PRICE," & _
"dbo_VENDOR2.ITEM_NO," & _
"dbo_VENDOR2.ITEM_PRICE," & _
"dbo_VENDOR1.MANUFACTURER_ITEM_NO," & _
"dbo_VENDOR1.MANUFACTURER," & _
"dbo_VENDOR1.ITEM_NAME " & _
"From dbo_VENDOR2 " & _
"INNER JOIN dbo_VENDOR1 " & _
"ON dbo_VENDOR2.MANUFACTURER_ITEM_NO = dbo_VENDOR1.MANUFACTURER_ITEM_NO " & _
"WHERE dbo_VENDOR1.MANUFACTURER IN ('MANUFACTURER CODE') " & _
"And dbo_VENDOR1.ITEM_PRICE > dbo_VENDOR2.ITEM_PRICE "
'Set rsSQL = dbs.OpenRecordset(StrSQL, dbOpenDynaset)
Dim qryName As String
qryName = "qryTest"
' close the query in case it is open in Access
DoCmd.SetWarnings False
DoCmd.Close acQuery, qryName
DoCmd.SetWarnings True
' Create the query based on the SQL string
createQry qryName, StrSQL
' Open the query in Access for display
DoCmd.OpenQuery qryName, acNormal, acReadOnly
End Sub

VBA Access SQL Server table insert

I have some problem when I deal with MS Access. I am using SQL Server and MS Access together.
I try to insert data into a new table.
First, this program asks me to add an item to the list (it is like temporary table). And then, there is another submit button which confirms the data (this step is needed and it is not inefficient one. Please do not ask about this step).
To add data to the list, I use a stored procedure. But I do not know what do I need to do to submit the data again.
Here is my code:
Dim rs As ADODB.Recordset
strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;"
Set conn = New ADODB.Connection
conn.Open strConn
cmd.ActiveConnection = conn
Set rs = New ADODB.Recordset
rs.Open "Insert into dbo.Blend values(List731.Column(1, introw),List731.Column(2, introw),TextRequestNo.Value, List731.Column(3, introw),List731.Column(4, introw),List731.Column(5, introw))"
conn.Close
Set rs = Nothing
MsgBox "Done"
When I run with this code, I get this error:
I think there is some missing in my code but I do not know how to proceed.
Is there anyone who can give me some information about this?
There are many ways to do this kind of thing. Something like this should get the job done.
Sub MoveDateFromAccessToSQLServer()
Dim adoCN As ADODB.Connection
Dim sConnString As String
Dim sSQL As String
Dim lRow As Long, lCol As Long
sConnString = "Provider=sqloledb;Server=servername;Database=NORTHWIND;User Id=xx;Password=password"
Set adoCN = CreateObject("ADODB.Connection")
'adoCN.Open sConnString
'Assumes that you have Field1, Field2 and Field3 in columns A, B and C
'Text values must be enclosed in apostrophes whereas numeric values should not.
sSQL = "INSERT INTO YOUR_TABLE (FIELD1, FIELD2, FIELD3) " & _
" VALUES (" & _
"'" & Column(1, introw) & "', " & _
"'" & Column(2, introw) & "', " & _
"'" & Column(3, introw) & "')"
adoCN.Execute sSQL
adoCN.Close
Set adoCN = Nothing
End Sub

Insert date from cell into sql table - Defaults to 1900-01-01

I can update an SQL table via Excel VBA except the date. The value comes through as 1900-01-01 or in some cases where I have played with the format it is shown as 1900-01-28.
It is a simple setup just for testing.
One Table with two columns CellText and CellDate, both getting their values from a cell range.
The value expected for CellText is 'Some Text'
The value expected for CellDate is 24/03/2015
Sub UpdateTable()
Dim cnn As ADODB.Connection
Dim uSQL As String
Dim strText As String
Dim strDate As Date
strText = ActiveSheet.Range("b4").Value
strDate = Format(ActiveSheet.Range("c4").Value, "dd/mm/yyyy")
Set cnn = New Connection
cnnstr = "Provider=SQLOLEDB; " & _
"Data Source=ServerName; " & _
"Initial Catalog=DbName;" & _
"User ID=UserName;" & _
"Trusted_Connection=Yes;"
cnn.Open cnnstr
uSQL = "INSERT INTO tbl_ExcelUpdate (CellText,CellDate) VALUES ('" & strText & "', " & strDate & ")"
Debug.Print uSQL
cnn.Execute uSQL
cnn.Close
Set cnn = Nothing
Exit Sub
End Sub
My Debug value is
INSERT INTO tbl_ExcelUpdate (CellText,CellDate) VALUES ('Some Text ', 24/03/2015)
My CellDate format in table is datetime.
Looks like you are missing single quotes on either side of the date.
INSERT INTO tbl_ExcelUpdate (CellText,CellDate) VALUES ('Some Text ', 24/03/2015)
Should be
INSERT INTO tbl_ExcelUpdate (CellText,CellDate) VALUES ('Some Text ', '24/03/2015')
Use CDate function to convert string formated date to date type
Sub UpdateTable()
Dim cnn As ADODB.Connection
Dim uSQL As String
Dim strText As String
Dim strDate As Date
strText = ActiveSheet.Range("b4").Value
strDate = Format(ActiveSheet.Range("c4").Value, "dd/mm/yyyy")
Set cnn = New Connection
cnnstr = "Provider=SQLOLEDB; " & _
"Data Source=ServerName; " & _
"Initial Catalog=DbName;" & _
"User ID=UserName;" & _
"Trusted_Connection=Yes;"
cnn.Open cnnstr uSQL = "INSERT INTO tbl_ExcelUpdate (CellText,CellDate) VALUES ('" & strText & "', " & CDate(strDate) & ")"
Debug.Print uSQL
cnn.Execute uSQL
cnn.Close
Set cnn = Nothing
Exit Sub
End Sub
you have to correct the strDate = Format(ActiveSheet.Range("c4").Value, "dd/mm/yyyy") to
strDate = Format(ActiveSheet.Range("c4").Value, "dd-mm-yyyy").
Then you have to put quotes:
uSQL = "INSERT INTO tbl_ExcelUpdate (CellText,CellDate) VALUES ('" & strText & "', '" & strDate & "')"

Export data from Excel to Access - Error: Argument not Optional

I'm trying to export data from Excel 2010 to Access 2010 with a VBA code on my excel file when I press a button. I just want to export the data from "Water Quality" sheet to the "Water Quality" table on my database (In the excel file and access file are other sheets and tables).
My actual code is:
Sub Button14_Click()
' Exports data from the active worksheet to a table in an Access database
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim r As Long
Dim LastRow As Long
' Set cn = New ADODB.Connection
'cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; " & _
"Data Source=C:\Documents and Settings\Administrador\Mis documentos\MonEAU\modelEAU Database V.2.accdb; " & _
"Persist Security Info=False;"
strCon = "Provider=Microsoft.ACE.OLEDB.12.0; " & _
"Data Source=C:\Documents and Settings\Administrador\Mis documentos\MonEAU\modelEAU Database V.2.accdb"
' Late binding, so no reference is needed
Set cn = CreateObject("ADODB.Connection")
cn.Open strCon
' Find LastRow in Col A into the Sheet1
LastRow = Sheet1.Range("A" & Rows.Count).End(xlUp).Row
' Insert unto a table called Water_Quality
scn = "[Excel 8.0;HDR=YES;DATABASE=" & ActiveWorkbook.FullName & "]"
strSQL = "INSERT INTO Water_Quality " _
& "SELECT * FROM " & scn & ".[Sheet1$A5:L" & LastRow & "]"
' Execute the statement
cn.Execute strSQL
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
I can debug without any problem the code but when I run it, a run error appears: "The Microsoft Office Access database engine could not find the object 'Sheet1$A5:L10'. Make sure the object exists and that you spell its name and the path name correctly." It seems that there's a problem with the line cn.Execute strSQL.
I've checked the names and the path name as well, and I can't find where the problem is.
Any help to solve it would be greatly appreciated.
Here are a few examples for inserting all the data at once:
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=z:\docs\test.accdb"
''Late binding, so no reference is needed
Set cn = CreateObject("ADODB.Connection")
cn.Open strCon
''Create a table called ATable
scn = "[Excel 8.0;HDR=YES;DATABASE=" & ActiveWorkbook.FullName & "]"
strSQL = "SELECT * INTO ATable " _
& "FROM " & scn & ".[Sheet7$A1:C4]"
''Execute the statement
cn.Execute strSQL
''Insert into a table called ATable
scn = "[Excel 8.0;HDR=YES;DATABASE=" & ActiveWorkbook.FullName & "]"
strSQL = "INSERT INTO ATable " _
& "SELECT * FROM " & scn & ".[Sheet7$A1:C4]"
''Execute the statement
cn.Execute strSQL
''Insert into a table with no column header in Excel,
''the fields are [afield],[atext],[another]
scn = "[Excel 8.0;HDR=NO;DATABASE=" & ActiveWorkbook.FullName & "]"
strSQL = "INSERT INTO ATable ([afield],[atext],[another]) " _
& "SELECT F1 As afield, F2 As AText, F3 As another FROM " _
& scn & ".[Sheet7$A1:C4]"
''Execute the statement
cn.Execute strSQL

transfer data from Excel to SQL Server

I have an Excel Spreadsheet that contains all my data that I need to put into an SQL Server database. I am fairly new o ASP.NET and have never had to export from Excel to SQL Server before.
My Excel spreadsheets looks like this
Trade Heading -> ArtID -> BusinessName -> AdStyleCode -> Address -> Suburb
In SQL Server I have created a table named "Listings" which is in this format
intListingID -> intCategoryID -> BusinessName - ArtID -> intAdCode ->Address -> Suburb
What would be the best way to export the data from Excel and then import it into SQLServer 2005.
Thanks...
You can do this easily using SSIS, you can refer to these two links for full details.
Link 1
Link 2
[EDIT]
If you have Express then you can try the below commands to setup a linked server and get the data
EXEC sp_addlinkedserver ExcelData,'Jet 4.0','Microsoft.Jet.OLEDB.4.0','C:\MyData.xls', NULL, 'Excel 5.0;'
GO
Then you can select the data into your tables
INSERT INTO Listings ...
SELECT column1 AS intListingID, <put all columns here> FROM ExcelData...Data
GO
For other options check this link
I tried exporting data from Excel to SQL server through VBA like this:
Const myDB As String = "tenant"
Const myServer As String = "MPAADM"
Const myDB As String = "new"
Const myServer As String = "arjun"
Sub ExportTableToSQL()
Dim cn As ADODB.Connection
Dim cnSQL As ADODB.Connection
Dim strSQL As String
Dim lngRecsAff As Long
Dim sqlTable As String
Dim acell As Range
Dim t1 As Date
Dim t2 As Date
Dim column As String
On Error Resume Next
path = Sheets("Sheet2").Range("B1").Value
Kill path & \z_temp\aa.xls"
Kill path & "\z_temp\aa.xls"
On Error GoTo 0
On Error GoTo 10
column = Cells(1, 1).Value
sqlTable = InputBox("Insert SQL table name")
Application.Wait (Now + TimeValue("0:00:2"))
t1 = Now
Debug.Print t1
If sqlTable = "" Then Exit Sub
Application.ScreenUpdating = False
Set acell = ActiveCell
If IsEmpty(ActiveCell) Then
MsgBox "Select a cell inside a table you want to export to SQL"
Exit Sub
End If
ActiveCell.CurrentRegion.Select
Selection.Copy
Call NewWorkbook
Cells(1, 1).Select
ActiveSheet.Paste
Set cn = New ADODB.Connection
Set cnSQL = New ADODB.Connection
With cnSQL
.ConnectionString = "provider=sqloledb;Data Source=" & myServer & ";Initial Catalog=" & myDB & ";Trusted_Connection=Yes"
' .ConnectionString = "provider=sqloledb;Data Source=" & myServer & ";Initial Catalog=" & myDB & ";Uid=jayantuser;Pwd=Input#123"
.Open
End With
ActiveWorkbook.SaveAs path & "\z_temp\aa.xls"
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & path & "\z_temp\aa.xls;" & _
"Extended Properties=Excel 12.0"
strSQL = "drop table " & sqlTable
Debug.Print strSQL
On Error Resume Next
cnSQL.Execute strSQL, lngRecsAff, adExecuteNoRecords
Err.Clear
On Error GoTo 10
strSQL = "SELECT * INTO [odbc;Driver={SQL Server};" & _
"Server=" & myServer & ";Database=" & myDB & _
";trusted_connection=yes]." & sqlTable & _
" FROM [sheet1$]"
Debug.Print strSQL
cn.Execute strSQL, lngRecsAff, adExecuteNoRecords
cn.Close
Set cn = Nothing
ActiveWorkbook.Close False
On Error Resume Next
Kill path & "\z_temp\aa.xlx"
On Error GoTo 0
t2 = Now
Debug.Print t2
MsgBox sqlTable & " table was successfully imported into SQL Server" & vbNewLine & "Transfered record number: " & lngRecsAff _
& vbNewLine & "Time:" & Int((t2 - t1) * 86400) & "s"
If MsgBox("Convert data type to bigint?", vbYesNo) = vbYes Then
strSQL = "ALTER TABLE " & sqlTable & " ALTER COLUMN " & column & " bigint"
cnSQL.Execute strSQL, lngRecsAff, adExecuteNoRecords
End If
Application.ScreenUpdating = True
acell.Select
Exit Sub
10: MsgBox Err.Description
End Sub `Sub NewWorkbook()
Application.DefaultSaveFormat = xlOpenXMLWorkbook
Workbooks.Add
End Sub`
`Sub Quit()
Application.Quit
End Sub`

Resources