c# - Inserting Scraped Results Into SQL Server -
any ideas why getting "an unhandled exception of type 'system.data.sqlclient.sqlexception' occurred in system.data.dll" when try insert results of sccraping sql server?
this code using:
public void scrape(string url) { using (sqlconnection opencon = new sqlconnection("connection string")) { string savestaff = "insert principale ((name) values (@name)"; opencon.open(); httpwebrequest request = (httpwebrequest)webrequest.create(url); request.useragent = "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1; sv1; .net clr 1.1.4322; .net clr 2.0.50727)"; request.allowautoredirect = false; webresponse response = request.getresponse(); streamreader streamreader = new streamreader(response.getresponsestream()); string html = streamreader.readtoend(); htmldocument page = new htmldocument(); page.loadhtml(html); var document = page.documentnode.selectnodes("//div[@class='b_namesummary']"); foreach (var nodo in document) { string nome = nodo.selectsinglenode("./h3[1]/a[1]").innertext; sqlcommand querysavestaff = new sqlcommand(savestaff); querysavestaff.connection = opencon; querysavestaff.parameters.add("@name", sqldbtype.nchar, 30).value = nome; querysavestaff.executenonquery(); console.writeline(nome); } } }
i think sql exception, apart obvious syntax error in missing closing parenthesis, (a typo?) comes fact declare parameter named @albergoname
in sql text use @name
placeholder instead
change to:
string savestaff = "insert principale (name) values (@albergoname)";
by way, don't need create sqlcommand inside loop, create outside , update parameter value
sqlcommand querysavestaff = new sqlcommand(savestaff); querysavestaff.connection = opencon; querysavestaff.parameters.add("@albergoname", sqldbtype.nvarchar, 30); foreach (var nodo in document) { string nome = nodo.selectsinglenode("./h3[1]/a[1]").innertext; console.writeline(nome); querysavestaff.parameters["@albergoname"].value = nome; querysavestaff.executenonquery(); }
notice have changed parameter type nvarchar instead of nchar. nchar fixed length type, if declare nchar 30 pass 30 characters whatever length of variable nome. suggest use nvarchar parameter type , set size same size of column name....
Comments
Post a Comment