OLEDB Parameterized Query

♀尐吖头ヾ 提交于 2019-11-26 17:26:10

问题


public void LoadDB()
{
    string FileName = @"c:\asdf.accdb";
    string query = "SELECT ID, Field1 FROM Table1 WHERE ID=? AND Field1=?";
    string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName;

    OleDbConnection odc = new OleDbConnection(strConn);
    dAdapter = new OleDbDataAdapter();
    OleDbCommand cmd = new OleDbCommand(query,odc);

    cmd.Parameters.Add("?", OleDbType.Integer, 5).Value = 1234;
    cmd.Parameters.Add("?", OleDbType.BSTR, 5).Value ="asdf";

    dAdapter.SelectCommand = cmd;

    ds = new DataSet();
    dAdapter.Fill(ds);
    dataGridView1.DataSource = ds.Tables[0];
}

I'm trying to use parametrized query to bind the access file into the datagridview. It finds the column names fine, but the contents are empty.

How can I fix this issue?


回答1:


In my test program, the ds.Tables[0].Rows.Count datatable actually had 1 row returned (as there was one row in my test database that matched the query itself). If you put a break on this line you should be able to see whether or not data is getting into the datatable in the first place. Try this:

dataGridView1.DataSource = ds.Tables[0];

What does the front end binding of dataGridView1 look like? Running the query in Access could shed some light on the situation too.




回答2:


Here is an example of how the parameterized queries work with CSharp, OleDB.

try
{
    connw.Open();
    OleDbCommand command;
    command = new OleDbCommand(
        "Update Deliveries " +
        "SET Deliveries.EmployeeID = ?, Deliveries.FIN = ?, Deliveries.TodaysOrders = ? , connw);
    command.Parameters.Add(new OleDbParameter("@EMPID", Convert.ToDecimal(empsplitIt[1])));
    command.Parameters.Add(new OleDbParameter("@FIN", truckSplit[1].ToString()));
    command.Parameters.Add(new OleDbParameter("@TodaysOrder", "R"));
    catchReturnedRows = command.ExecuteNonQuery();//Commit   
    connw.Close();

}
catch (OleDbException exception)
{
    MessageBox.Show(exception.Message, "OleDb Exception");
}

This will work with any sql statement, you must assign the question mark "?" to each parameter, and then below you must create the parameters and add them in the order of how you laid out the question marks to get the right data into the right field.




回答3:


Try without specifying column size in parameters:

cmd.Parameters.Add("?", OleDbType.Integer).Value = 1234;
cmd.Parameters.Add("?", OleDbType.BSTR).Value ="asdf";


来源:https://stackoverflow.com/questions/12048152/oledb-parameterized-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!