Link to home
Start Free TrialLog in
Avatar of kshumway
kshumwayFlag for United States of America

asked on

Transfer data from .csv file into SQL table via vb.net

I need to convert an MS Access program to VB.NET and move the back end to SQL Server.  The current program reads a .csv file and via docmd.transfertext, pull the data from the csv file into the table.  How would I do that in VB.Net?
Avatar of David L. Hansen
David L. Hansen
Flag of United States of America image

Try this, I can help if it doesn't quite do what you need.  I think you'll be pleased with this solution however.

http://www.daniweb.com/software-development/vbnet/threads/52051
Avatar of kshumway

ASKER

sl8rz,
 
I'm gettng an error on MSDASQL, I believe because its for an OLEDB.  The data is being transferred into a SQL table.  How would I change the line below if it's being read into a SQL Table.

"Select * " & _
                       " INTO HospitalInvoice.dbo.[Hospital Billing Data SQL] " & _
                      "FROM  OPENROWSET('MSDASQL','Driver={Microsoft Text Driver (*.txt; *.csv)}; DEFAULTDIR=\\Kfs\Finance\Hospital Invoices\; Extensions=txt; HDR=No;','SELECT * FROM CGHCharges.txt') "

Thank you so much for your help!
Is there a Schema.ini file in your csv's directory?  If so, open it and change the 'ColNameHeader=True' line to 'ColNameHeader=False'.
There is no schema.ini file.
Attached is the error message I am getting.  Should I have a Schema.ini file?  Your help is greatly appreciated.

 Error.doc
CodeCruiser - can you help?
I am new to this.  My understanding after some research is that the Schema.ini file is similar to the specification in Access.  Do you have a sample Schema.ini file so I can see the format and then I can create the file in the directory where the .csv file is located?  Thank you!
CodeCruiser,

For the Bulk Import, I would create a stored procedure in my SQL Database, correct?  How would I call that procedure from VB.Net?  This is a windows application.  Thank you so much for your help.
sl8rz

Is the DefaultDir clause the directory (folder) where the text file is located?  Thank you for your help!
CodeCruiser,

I read a little on the bulk insert and it sounds like what I want. as it is very quick.  I have a table already created and I tried to create a stored procedure to do the import.  I can't get that to work.  I need to have a process that can be run from a windows application, which either drops and then creates the table and imports the data or clears the existing table and imports the data.  Is a store procedure the right way to go?  Can you call a script from VB.NET?  Could you possibly help me with the code?  I would truly appreciate your help.  This is an important project and I'm sinking!

Thank you.
Kathy
Still there?  Sorry for dropping off like that...big weekend.  I'll keep looking into this for you.  I'm sure we'll get it working for you; it is a commonly encountered request.  Please, let me know where you are at this point.
I've attached the error I was getting in Error.doc.  Below is my code.  If I understanding what I've read correctly, it should create a Schema.INI file in the directory where the data file exists.  If that's correct, it's not happening.  Any help would be greatly appreciated!


If File.Exists(sHospDataFile) Then
            Try
                conn.Open()
                ' ------ Load the data from the .CSV file: ----------
                Dim strSQL As String
                strSQL = "Select * " & _
                       " INTO HospitalInvoice.dbo.[Hospital Billing Data SQL] " & _
                      "FROM  OPENROWSET('MSDASQL','Driver={Microsoft Text Driver (*.txt; *.csv)}; DEFAULTDIR=C:\Data\; Extensions=csv; HDR=No;','SELECT * FROM HospitalInvoicesData.csv') "
                              Dim objCommand As SqlClient.SqlCommand
                objCommand = New SqlClient.SqlCommand(strSQL, conn)

                objCommand.CommandText = strSQL
                objCommand.ExecuteNonQuery()
                conn.Close()
            Catch ex As Exception
                sResultText = sResultText & "<BR>" & ex.Message
                MsgBox(sResultText)
            End Try
        End If

Open in new window

What is the error and on which line does it occur?
I'll attach it again. Error.doc
So your HospitalInvoicesData.csv file does exist in C:\Data\  ?
I copied it to c:\Data\ to see if the problem was that I was trying to access it off the server -  \\cimadhoc\Data Sources\hospitalinvoicesdata.csv.  I adjusted the location in the code and I get the same error no matter where the file is located.  Attached is the code if the file is on the server.
If File.Exists(sHospDataFile) Then
            Try
                conn.Open()
                ' ------ Load the data from the .CSV file: ----------
                Dim strSQL As String
                strSQL = "Select * " & _
                       " INTO HospitalInvoice.dbo.[Hospital Billing Data SQL] " & _
                      "FROM  OPENROWSET('MSDASQL','Driver={Microsoft Text Driver (*.txt; *.csv)}; DEFAULTDIR=\\cimadhoc\Data Sources\hospitalinvoicesdata.csv; Extensions=csv; HDR=No;','SELECT * FROM HospitalInvoicesData.csv') "
                Dim objCommand As SqlClient.SqlCommand
                objCommand = New SqlClient.SqlCommand(strSQL, conn)

                objCommand.CommandText = strSQL
                objCommand.ExecuteNonQuery()
                conn.Close()
            Catch ex As Exception
                sResultText = sResultText & "<BR>" & ex.Message
                MsgBox(sResultText)
            End Try
        End If

Open in new window

s18rz

I also tried the bulk insert option that codecruiser suggested.  I'm getting an error that the csv file cannot be accessed.  Could the errors I am getting with the option you suggested be related to access of the data file?  Our network administrator is looking into the issue and we've tried a number of things with no luck.  Any ideas?  Attached is that error Error2.doc
Using a stored procedure is a more robust solution, so let's work that option for now.

The error is saying that the csv file can not be opened in that location; is it there in that folder?  Also, let's see the script for the stored procedure.
The file is there and I can access it.  Attached is the stored procedure script.  I truly appreciate your help!
ALTER PROCEDURE dbo.InsertHospitalData
as
begin
BULK INSERT [Hospital Billing Data SQL]
FROM '\\Cimadhoc\Data Sources\HospitalInvoicesData.csv'
WITH 
	(
	FIELDTERMINATOR = ',',
	ROWTERMINATOR = '\n'
	)
END

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I get the same error when I try to run the stored procedure against the csv file inmy c:\Data\HospitalInvoicesData.csv.  But if I  move the file to my c:\ drive (c:\HospitalInvoicesData.csv) the error message states the file does not exist...  But it's there.  I am very confused.

I would think its UAC. Try another drive (d:, e: etc) if you have one.
The only local drive I have is the C:\ drive.
I provided some mis-information.  The error message was cut off and I assumed it was the same as the drror message when the datafile was on the cimadhoc server.  If the data file is in the C:\Data\ folder the error message is:

Could not bulk insert because file 'C:\Data\HospitalInvoicesData.csv' could not be opened. Operating system error code 3(The system cannot find the path specified.).

It appears that my project folder for Visual Studiio 2008 is pointing to my MyDocuments folder which is on a server, no my local workstation.  Not sure if that has any affect on SQL Server finding my C:\ drive.  I'm grasping here, but wanted to give you all the information that I have about my configuration.
And as one last ditch effort, I copied the csv file to My Doucments folder (\\kfs\users\l92241) and I got the same error message I got when it's located on the Cimadhoc server.  
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sorry for the delay - had to drive home.  

Ok - SQL Server is installed on the server.  I found a project folder under \Microsoft SQL Server\MSSQL\FTData \SQLServer \ Projects.  Is that the folder?  I'm going to copy it there and see what happens.  If that's not the folder you are referring to, please let me know.  Thank you!
OK - this may be a stupid questions, but how do I reference the c:\ drive on another server is it's not shared out?  

Server = \\KSQLDB
File Path = C:\Program Files\Microsoft SQLServer\MSSQL\FTDATA\SQLServer\Projects

Referencing any folder residing on another computer requires that the other folder be shared in some way.
But if you have access to it anyway then you can use

\\KSQLDB\c$\...


>Operating system error code 3
This error usually means that the file is there but SQL server is unable to access it.
I used the following path\filename:
'\\KSQLDB\c$\Program Files\Microsoft SQLServer\MSSQL\FTDATA\SQLServer\Projects\HospitalInvoicesData.csv'

and got the following error message:

Could not bulk insert because file '\\KSQLDB\c$\Program Files\Microsoft SQLServer\MSSQL\FTDATA\SQLServer\Projects\HospitalInvoicesData.csv' could not be opened. Operating system error code 3(The system cannot find the path specified.).
I sent an email to our network administrator asking if he could tempoarily create a share to the project folder so we could test.  I''m in meetings this morning but will check back to see if he was able to create the share.

BTW, on KSQLDB, we are running SQL Server 2000.  It's slated to be upgraded sometime this Fall.

Thank you again for all your hellp.
Dave created the share and I tested it.  Worked like a charm.  Worse case is that I have to copy the file to that directory...  Can I easily do that in my code?  I'm off to meetings, but will be back later.  
Good to hear you are making progress.

Yes, moving a file in your VB code is very easy.  It's in the IO namespace, here is an example:
System.IO.File.Move('C:\myFolder\myFile.csv', '\\myNetworkPlace\myFileCopy.csv')

Open in new window

First of all, I'd like to thank both of you for your help.  This was definitely a life saver.  I have a meeting tomorrow that I can now give a positive report on.  I found the code to copy the file from the \\cimadhoc server to the share on \\ksqldb\projects.  Along with the bulk copy I have the data in the e table.  It's very fast!

Since you both helped, I'd like to split the the points if that's okay.  Let me know.
We must have been writing at the same time.  That's exactly what I used.  Thank you!!!
Welcome...split the points however you feel is best.  Glad we could help you slay the dragon :)
Thank you!!!!!!
Thank you so much for all your help.  This was a lifesaver!