I am using an ASP page where I have to read a CSV file and insert it into DB table "Employee". I am creating an object of TestReader. How can I write a loop to execute up to the number of rows/records of the CSV file which is being read?
Do not try to parse the file yourself, you'll just give yourself a headache. There's quite a bit more to it than splitting on newline and commas.
You can use OLEDB to open up the file in a recordset and read it just as you would a db table. Something like this:
Dim strConn, conn, rs
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
Server.MapPath("path to folder") & ";Extended Properties='text;HDR=Yes;FMT-Delimited';"
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open strConn
Set rs = Server.CreateObject("ADODB.recordset")
rs.open "SELECT * FROM myfile.csv", conn
while not rs.eof
...
rs.movenext
wend
My vbscript is rusty, so verify the syntax.
edit: harpo's comment brings up a good point about field definitions. Defining a schema.ini file allows you to define the number and datatypes of the expected fields. See: You can handle this by defining a schema.ini file. see: http://msdn.microsoft.com/en-us/library/ms709353.aspx
Why not just insert the CSV? For example:
SELECT * INTO MyTable FROM OPENDATASOURCE('Microsoft.JET.OLEDB.4.0',
'Data Source=F:\MyDirectory;Extended Properties="text;HDR=No"')...
[MyCsvFile#csv]
From: http://coding.derkeiler.com/Archive/Delphi/borland.public.delphi.database.ado/2007-05/msg00057.html
Related
I want to import data (not structure) from Access to SQLite via ODBC
and it works, but there is one point that is annoying:
I don't want to create a new table automatically - I want to import data into my existing table and I get the following error:
ODBC--call failed
table "x" already exists(1)(#1)
I want to find a way to avoid creating new table in sqlite.
I have also tried another solution for importing my data from Access to SQLite via csv. However, my encoding is utf-8 but it shows data as question marks!
There are many ways to move data around using Access.
When appending data to ODBC tables, I recommend the following steps:
Create a linked table to the ODBC table you want to import to in Access using Import -> ODBC database
Use an append query to move the data from the local table to the ODBC table
(optional) Remove the linked table.
Alternatively, Access can directly run append queries to ODBC data sources without creating linked tables, but this requires some SQL knowledge. Syntax is the following:
INSERT INTO [ODBC;MyDSNOrConnectionString].[MyRemoteTable] (Field1, Field2, FieldN)
SELECT Field1, Field2, FieldN
FROM MyLocalTable
There is another way of exporting Access table records into an exisitng ODBC table with Adobe connection, if the tables on both side have the same name and the same structure and if the table structure is stored in a system table.
Dim Str_Sql As String
Dim Conn As New ADODB.Connection
Dim myDSN As String
Dim UserName As String
Dim Password As String
Dim Rs_Tabl As DAO.Recordset
Dim Rs_TablStru As DAO.Recordset
myDSN = ...
UserName = ...
Password = ...
Conn.Open "dsn=" & myDSN & ";uid=" & UserName & ";pwd=" & Password
Set cmd = CreateObject("ADODB.Command")
Set cmd.ActiveConnection = Conn
Set Rs_Tabl = CurrentDb.OpenRecordset(TablName)
Set Rs_TablStru = CurrentDb.OpenRecordset("select * from Systable where TableName=TableName order by ColumnOrder")
Str_Sql = "truncate table TableName"
Conn.Execute (Str_Sql)
Str_Sql = "insert into TableName values ('"
Do Until Rs_Tabl.EOF
Str_Sql = "insert into TableName values ('"
Rs_TablStru.MoveFirst
Do Until Rs_TablStru.EOF
Str_Sql = Str_Sql & Rs_Tabl.Fields(Rs_TablStru.Fields("AAA")) & "','"
Rs_TablStru.MoveNext
Loop
Str_Sql = Mid(Str_Sql, 1, Len(Str_Sql) - 2) & ")"
Debug.Print Str_Sql
Conn.Execute (Str_Sql)
Rs_Tabl.MoveNext
Loop
Rs_Tabl.Close
Rs_TablStru.Close
Set Rs_Tabl = Nothing
Set Rs_TablStru = Nothing
Conn.Close
*AAA:A column from system table that stores column names from all tables.
I am populating a DataSet with data from an excel sheet. I now need to insert this data into a table in an Access database that has identical structure.
Convention would dictate that I iterate over the rows of the DataTable and make an INSERT query for each, but I was wondering if there is a more efficient way to accomplish this? Perhaps something analogous to SqlBulkCopy for SQL Server?
Here is the code I have so far:
Dim connection As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Server.MapPath(path) & ";Extended Properties=Excel 12.0;")
Dim adapter = New OleDbDataAdapter("SELECT * FROM [Sheet1$] WHERE EmpID IS NOT NULL", connection)
Dim results = New System.Data.DataSet
connection.Open()
adapter.Fill(results)
connection.Close()
connection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Server.MapPath("~/App_Data/Leaves.accdb"))
`Now, short of a loop, how can I insert results.Tables(0) into my database?
Thanks for your help.
You can use ADO, for example:
INSERT INTO Table1 ( ADate )
SELECT SomeDate FROM [Excel 8.0;HDR=YES;DATABASE=Z:\Docs\Test.xls].[Sheet1$a1:a4]
Where the connection is to the Access database. If you wish to use the whole sheet, refer to [Sheet1$] as your table, if you wish to use a named range, just refer to it by name.
I am having some trouble getting the correct syntax for a bit if code. I am using vb to insert data into a db and outputting the data as XML, here is the code
<WebMethod()> _
Public Function addTrack(ByVal tTitle As String, ByVal tAlbum As String, ByVal tGenre As String) As String
Dim conn As New SqlConnection("Data Source=MARTIN-LAPTOP\SQLEXPRESS;Initial Catalog=mp3_playlists;Integrated Security=True")
Dim sql As String = "INSERT INTO Tracks (trackTitle, trackAlbum, trackGenre) VALUES ('" & tTitle & "', '" & tAlbum & "', '" & tGenre & "') FOR XML AUTO, ELEMENTS"
conn.Open()
Dim cmd As New SqlCommand(sql, conn)
Dim track As String = cmd.ExecuteScalar()
conn.Close()
Return track
End Function
The code is for a ASP.NET web service, when I click invoke on the website i get the error Incorrect syntax near the keyword 'FOR'. If I remove FOR XML AUTO, ELEMENTS everything works find, db updates but I dont get the data to output as XML. I think the issue is with
the brackets required for the insert values because this issue does not occur if the SQL statement is a SELECT statement which has no brackets but i just cant figure out the correct syntax, thanks for your help
FOR XML AUTO is only used for SELECT statements. So, the issue is not your insert statement, it is your select statement, whereever that is.
I have to make an quick update on a legacy asp page never really having done anything with classical asp want to check if this is valid.
Can I do this:
set conn = server.CreateObject("ADODB.Connection")
conn.Open ("connection string info")
Set rsIdent = server.CreateObject("ADODB.Recordset")
SQL = "EXEC procedureName #sParam = '" & someVariable & "'"
rsIdent.Open SQL, conn
iSome_ID = rsIdent.Fields("ident_value")
rsIdent.Close()
Set rsIdent = nothing
Where procedureName is a stored procedure that accepts a paramter, does some processing and returns a single record in a column called "ident_value"?
#Curtis: See How to call SQL Server stored procedures from ASP.
I'm trying to avoid using straight SQL queries in my web app. I looked around and have come to the conclusion that ADO Recordsets would be the best or at least safest tool for the job. I need to insert records into a database table. Unfortunately I'm at a loss as to how to get the identity value for the record which was just inserted. Here's a reduction of what I've got now:
<%
dim insertID, rs
set rs = Server.CreateObject("ADODB.Recordset")
rs.Open "my_table_name", conn, adOpenForwardOnly, adLockOptimistic
rs.AddNew()
Call m_map_values_to_rs(rs)
rs.Update()
insertID = rs("id")
rs.Close()
rs = Nothing
%>
The code I have is successfully inserting the record, but I can't for the life of me figure out how to get the id field of the Recordset to update after the insert. How can I get the identity column value back from this Recordset?
UPDATE - Here's the solution with regard to the code above.
I had to change the cursor type to adOpenKeyset instead of adOpenForwardOnly. After I did this the record is automatically updated with the "auto number" field's new value after the insert. However it is not what you think it is. The value of rs("id") doesn't become an integer or even a variant. It becomes some sort of Automation type and cannot be evaluated as a number. Nor can CInt() be used directly on that type for some reason. So what you must do is to convert the value to a string and then convert it to an Int. Here's how I managed that:
insertID = CInt( rs("id") & "" )
Thanks to Dee for their answer. It helped immensely.
This article explains the means of getting identity value with example code.
The relevant code snippet is:
<%
fakeValue = 5
set conn = CreateObject("ADODB.Connection")
conn.open "<conn string>"
sql = "INSERT someTable(IntColumn) values(" & fakeValue & ")" & _
VBCrLf & " SELECT ##IDENTITY"
set rs = conn.execute(sql)
response.write "New ID was " & rs(0)
rs.close: set rs = nothing
conn.close: set conn = nothing
%>