c# - How to skip first 2 lines and last line when I use BULK INSERT -
hi have application whereby user browese csv file , the data in csv file should written table using bulk insert
the text file looks this
student_head 201501 student_id code amount 1 salb 10015 2 salb 10016 3 salb 10017 4 c100 4000 5 salb 10022 end
what need skip first 2 lines , last line.
i should this:
1 salb 10015 2 salb 10016 3 salb 10017 4 c100 4000 5 salb 10022
i have tried code nothing seems happening
openfiledialog1.filter = ".csv file|*.csv*"; openfiledialog1.filterindex = 1; dialogresult result = openfiledialog1.showdialog(); if (result == dialogresult.yes) { string file = openfiledialog1.filename; using (var reader = new streamreader(file)) { string firstline = reader.readline(); string[] splitedline = firstline.split(';'); string month = splitedline[1]; } try { string connect = "data source=george-pc\\sqlexpress; initial catalog=students; user id =sa; password=george1"; sqlconnection con = new sqlconnection(connect); con.open(); string bulkinsert = "bulk insert t_original from" + file + "with (firstrow = 3," + "fieldterminator = ''," + "maxerrors = 0," + "rowterminator = '\\n')"; //"update t_original"+ //"set month =" + month + //"where month null"; sqlcommand bulkcmd = new sqlcommand(bulkinsert, con); bulkcmd.executenonquery();
any , advise appreciated
thank you
instead of using sqlcommand
, try using sqlbulkcopy
object.
something like...
datatable table = new datatable(); //turn csv data datatable using favorite csv parser. //my favorite [`textfieldparser`][2]. using sqlbulkcopy copier = new sqlbulkcopy(connectionstring, sqlbulkcopyoptions.keepidentity or sqlbulkcopyoptions.keepnulls) { // set column mappings via sqlbulkcopy.columnmappings // choose destination table sqlbulkcopy.destinationtablename // execute copy copier.writetoserver(table); }
Comments
Post a Comment