Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

c# - OLEDB Parameterized Query

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...