嘿所有我意识到之前已经问过这个问题,但即使我按照答案,我仍然无法让我的代码工作。错误发生在“data_adapter.Fill(temp_table)”,任何有关正在发生的事情的帮助都将受到赞赏。
string ConnStr = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = H:\\School Work\\Computing A Level\\Stock checker\\Program\\Morgan's Motors Database.mdb";
string Query = "SELECT * FROM [Car Info] WHERE @x ";
string FirstQuery = null;
int i = 0;
for (i = 0; i < ColumnName.Count - 1; i++)
{
FirstQuery += string.Format("{0} = {1} AND ", ColumnName[i], EnteredFields[i]);
}
FirstQuery += string.Format("{0} = {1}", ColumnName[i], EnteredFields[i]);
MessageBox.Show(Query);
OleDbConnection database_connection = new OleDbConnection(ConnStr);
OleDbCommand database_command = new OleDbCommand(Query, database_connection);
database_command.Parameters.AddWithValue("@x", FirstQuery);
OleDbDataAdapter database_adapter = new OleDbDataAdapter();
database_adapter.SelectCommand = new OleDbCommand(database_command.CommandText, database_connection);
DataTable temp_table = new DataTable();
database_adapter.Fill(temp_table);
BindingSource data_source = new BindingSource();
data_source.DataSource = temp_table;
dataGridView1.DataSource = data_source;
编辑:我在重组代码方面取得了一些进展,现在的问题是“?”没有被替换
string ConnStr =“Provider = Microsoft.ACE.OLEDB.12.0; Data Source = H:\ School Work \ Computing A Level \ Stock checker \ Program \ Morgan's Motors Database.mdb;”;
OleDbConnection conn_database = new OleDbConnection();
conn_database.ConnectionString = ConnStr;
OleDbCommand comm_database = new OleDbCommand();
comm_database.CommandText = "SELECT * FROM [Car Info] WHERE ? = ?";
comm_database.Connection = conn_database;
OleDbDataAdapter adap_database = new OleDbDataAdapter(comm_database);
DataTable data_database = new DataTable();
for (int i = 0; i < ColumnName.Count; i++)
{
comm_database.Parameters.AddWithValue("?", ColumnName[i].ToString());
comm_database.Parameters.AddWithValue("?", EnteredFields[i].ToString());
MessageBox.Show(adap_database.SelectCommand.CommandText);
adap_database.Fill(data_database);
}
BindingSource bind_database = new BindingSource();
bind_database.DataSource = data_database;
dataGridView1.DataSource = bind_database;
答案 0 :(得分:0)
你有没有尝试过:
database_command.Parameters.AddWithValue("@x", EnteredFields[i]);
而不是:
database_command.Parameters.AddWithValue("@x", FirstQuery);
通常在使用参数时,您只需添加参数名称及其值,而不必将columnName =添加到值中。有意义吗?
如果想要利用参数,您可以尝试的一件事是下面的代码。我不知道它是否能解决您的问题,但至少它有助于保护您免受SQL注入攻击。请让我知道,如果你有任何问题。
string Query = "SELECT * FROM [Car Info] WHERE {0} ";
for (i = 0; i < ColumnName.Count - 1; i++)
{
FirstQuery += string.Format("{0} = @{1} AND ", ColumnName[i], ColumnName[i]);
}
FirstQuery += string.Format("{0} = @{1}", ColumnName[i], ColumnName[i]);
Query = String.Format(Query, FirstQuery);
for (i = 0; i < ColumnName.Count - 1; i++)
{
database_command.Parameters.AddWithValue("@" + ColumnName[i], EnteredFields[i]);
}