这很简单,但我看不出错误在哪里!该参数未添加到查询中。这是我的代码:
SQLiteDB db;
db = new SQLiteDB(Config.getMasterUsersDB());
DataTable masterUsers;
SQLiteCommand query = new SQLiteCommand("SELECT username , password , localDB FROM master_users WHERE username = @username");
query.Parameters.Add("@username", comboMasterUsers.SelectedItem.ToString());
masterUsers = db.GetDataTable(query.CommandText);
foreach (DataRow r in masterUsers.Rows)
{
if (txtPassword.Text == r["password"].ToString())
{
Config.setLocalDB(r["localDB"].ToString());
Config.setLoggedMasterUser(r["username"].ToString());
this.Hide();
formMain formMain = new formMain();
formMain.Show();
}
}
SQLiteDB是一个用于进行数据库连接和检索的辅助类
public DataTable GetDataTable(string sql)
{
DataTable dt = new DataTable();
try
{
SQLiteConnection cnn = new SQLiteConnection(dbConnection);
cnn.Open();
SQLiteCommand mycommand = new SQLiteCommand(cnn);
mycommand.CommandText = sql;
SQLiteDataReader reader = mycommand.ExecuteReader();
dt.Load(reader);
reader.Close();
cnn.Close();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
return dt;
}
为什么我会将错误的参数提供给命令错误?我也看不到任何拼写错误。
答案 0 :(得分:0)
您要将参数添加到第一个命令对象(query
),然后创建一个没有任何参数的第二个对象(mycommand
)。
您必须更改GetDataTable
才能将参数添加到自己的对象中:
...
string sql = "SELECT ... WHERE username = ?";
db.GetDataTable(sql, comboMasterUsers.SelectedItem.ToString());
...
public DataTable GetDataTable(string sql, params Object[] parameters)
{
...
mycommand.CommandText = sql;
foreach (var value in parameters)
{
var param = mycommand.CreateParameter();
param.Value = value;
mycommand.Parameters.Add(param);
}
...