Execute SQL command and output result to DataGridView in C# -
i trying execute sql command on access database on oledbconnection using c# , use information fill datagridview on windows form. have opened connection, stated query, , executed it, cannot find how output results datagridview on windows form (named dataoutput).
private void query() { string cmdtext = "select * retentiontable " + "where [datetime] between '" + getdatetimefrom("") + "' , '" + getdatetimeto("") + "'"; string connectionpath = "provider=microsoft.jet.oledb.4.0;data source=retentiondb.mdb"; try { oledbconnection cn = new oledbconnection(connectionpath); dataset objdataset = new dataset(); oledbdataadapter objdataadapter = new oledbdataadapter(); if (cn.state.equals(connectionstate.closed)) { cn.open(); } oledbcommand oledbsearch = new oledbcommand(cmdtext, cn); oledbsearch.executenonquery(); objdataadapter.fill(objdataset); dataoutput.datasource = objdataset; cn.close(); } catch (exception ex) { messagebox.show(ex.message.tostring()); messagebox.show(ex.stacktrace.tostring()); } }
from can see, query being executed correctly, issue comes when trying use objdataadapter.fill. guess not understanding how fill dataset output query. appreciated. thanks!
a few comments:
- your query subject sql injection. use parameterised query instead.
- you don't need open/close connection;
dataadapter
you. - you should wrap
oledbconnection
,oledbcommand
objects inusing
block ensure resources cleaned up. - you don't need call
executenonquery
, or otherexecute...
method on command; - you need assign command
selectcommand
property ofoledbdataadapter
, or pass constructor.
try this:
private void query() { const string connectionpath = "provider=microsoft.jet.oledb.4.0;data source=retentiondb.mdb"; try { using (var cn = new oledbconnection(connectionpath)) using (var cmd = new oledbcommand("select * retentiontable [datetime] between ? , ?")) { // parameter names don't matter; oledb uses positional parameters. cmd.parameters.addwithvalue("@p0", getdatetimefrom("")); cmd.parameters.addwithvalue("@p1", getdatetimeto("")); var objdataset = new dataset(); var objdataadapter = new oledbdataadapter(cmd); objdataadapter.fill(objdataset); dataoutput.datasource = objdataset; } } catch (exception ex) { messagebox.show(ex.message.tostring()); messagebox.show(ex.stacktrace.tostring()); } }
Comments
Post a Comment