c# - SQLBulkCopy - WriteToServer method not working -
i'm trying export data excel file mdf database. that, i'm using excel data reader , sql bulk copy :
using system; using system.collections.generic; using system.linq; using system.text; using system.io; using excel; using system.data; using system.diagnostics; using system.data.sqlclient; namespace bulktest { class program { static void main(string[] args) { filestream fs = file.open(@"c:\users\maarab\desktop\list_personnel 2013.xlsx", filemode.open, fileaccess.read); iexceldatareader excelreader = excelreaderfactory.createopenxmlreader(fs); datatable dt = createdatatable(); string cx = @"data source=.\sqlexpress;attachdbfilename=|datadirectory|\datatest.mdf;integrated security=true;user instance=true"; sqlbulkcopy bcp = new sqlbulkcopy(cx, sqlbulkcopyoptions.keepidentity); bool first = true; while (excelreader.read()) { if (first) { first = false; } else { if (string.isnullorwhitespace(excelreader.getstring(0))) break; else { string numnat = excelreader.getstring(2); datetime birthdate = excelreader.getdatetime(9); datetime startdate = excelreader.getdatetime(1); if (!string.isnullorwhitespace(numnat)) { if (numnat.length == 12) { numnat = numnat.remove(6, 1); } } if (birthdate.year < 1753) birthdate = datetime.now; if (startdate.year < 1753) startdate = datetime.now; dt.rows.add(excelreader.getstring(0), excelreader.getstring(0), numnat, startdate, birthdate); } } } bcp.destinationtablename = "person"; bcp.batchsize = 100; bcp.columnmappings.add(0, 1); bcp.columnmappings.add(1, 2); bcp.columnmappings.add(2, 3); bcp.columnmappings.add(3, 4); bcp.columnmappings.add(4, 5); try { bcp.writetoserver(dt, datarowstate.unchanged); } catch (exception e) { console.writeline(e.message); } console.readline(); } public static datatable createdatatable() { datatable dt = new datatable(); dt.columns.add("firstname", typeof(string)); dt.columns.add("lastname", typeof(string)); dt.columns.add("numnat", typeof(string)); dt.columns.add("birthdate", typeof(datetime)); dt.columns.add("startdate", typeof(datetime)); return dt; } } }
i'm filling datatable excel file , goes good. program running without problem unfortunatelly there's no insert table. idea solve that?
if @ table using server explorer should check connection used in window. happens have database file listed in project files , connection used server explorer points file in project folder.
of course, when program runs, connection used 1 specified in app.config.
in scenario have no error (because no error exists) server explorer wrong database no action occured , can't see updates.
solution easy, need reconfigure connection used server explorer point effective value of |datadirectory| substitution string (usually bin\debug or bin depending on project type)
Comments
Post a Comment