在我的Insert查询语句中使用WHERE

时间:2014-01-05 11:56:35

标签: c# select oledb where-clause

string conString = @"Provider=Microsoft.ACE.OLEDB.12.0;
           Data Source=C:\Users\user\Documents\Visual Studio 2010\Projects\Timetable\Timetable\bin\Debug\timetabledata.accdb";

//create the database query
string query = "SELECT * FROM relation";

OleDbConnection conn = new OleDbConnection(conString);
conn.Open();

// create the DataSet
DataSet ds = new DataSet();

// create the adapter and fill the DataSet
OleDbDataAdapter adapter;
adapter = new OleDbDataAdapter(query, conn);
adapter.Fill(ds);

int f = ds.Tables[0].Rows.Count;
int i;
for (i = 0; i < f; i++)
    {
     // create the database query
     string query1 = "SELECT * FROM [time] Where classid= '"+
                               ds.Tables[0].Rows[i].ItemArray[2]+"'";
     DataSet ds1 = new DataSet();
     OleDbDataAdapter adapter1;
     adapter1 = new OleDbDataAdapter(query1, conn);
     adapter1.Fill(ds1);
     MessageBox.Show(ds1.Tables[0].Rows[0].ItemArray[0].ToString());
     }

我在消息框中得不到的结果是我想要所有行的id具有相同的classid但是在消息框中我只是用来验证o之前继续我看到时间表的id而不考虑在哪里< / p>

2 个答案:

答案 0 :(得分:1)

不应该从......改变这部分。

string query1 = "SELECT * FROM [time] Where classid+ '"+
                               ds.Tables[0].Rows[i].ItemArray[2]+"'";

为...

string query1 = "SELECT * FROM [time] Where classid = '"+
                               ds.Tables[0].Rows[i].ItemArray[2]+"'";

您似乎使用加号( + )而不是等号( = )。

答案 1 :(得分:0)

试一试:

public DataSet GetRelations()
{
    using (var connection = new OleDbConnection(ConnectionString))
    {
        connection.Open();
        using (var adapter = new OleDbDataAdapter("SELECT * FROM [relation]", connection))
        {
            var results = new DataSet();
            adapter.Fill(results);
            return results;
        }
    }
}

public DataSet GetTimeResults()
{
    DataSet dsRelations = GetRelations();

    var dsResults = new DataSet();
    using (var connection = new OleDbConnection(ConnectionString)) 
    {
        connection.Open();

        foreach (DataRow row in dsRelations.Tables[0].Rows)
        {
            using (var command = new OleDbCommand("SELECT * FROM [time] Where classid = ?", connection))
            {
                // not entirey sure what the value of row.ItemArray[2] is ?
                command.Parameters.Add(row.ItemArray[2]);
                using (var adapter = new OleDbDataAdapter(command))
                {
                    adapter.Fill(dsResults);
                }
            }
        }
    }
    return dsResults;
}

只需调用它并按照您认为合适的方式使用它:

public void Test()
{
    DataSet dsTimeResults = GetTimeResults();
    // Do whatever you need with the results
}