我试图让一个简单的SQLite数据库工作。我正在使用C#的官方SQLite扩展,我使用IntelliJ的DataGrip来验证数据是否存在,但我的C#程序没有得到任何结果。
这是执行查询的代码:
SQLiteConnection connection = new SQLiteConnection(DbDsn);
User user = new User();
using (connection)
{
connection.Open();
string sql = "SELECT * FROM user WHERE username = @username ;";
SQLiteCommand command = new SQLiteCommand(sql, connection);
command.Prepare();
command.Parameters.AddWithValue("@username", username);
SQLiteDataReader reader = command.ExecuteReader();
if (reader.Read())
{
user.Id = (int) reader["id"];
user.Username = reader["username"] as string;
user.Password = reader["password"] as string;
user.Name = reader["name"] as string;
user.LastName = reader["last_name"] as string;
user.Type = (UserTypes) reader["type"];
}
else
{
throw new ObjectNotFoundException();
}
connection.Close();
}
这是对用户表进行简单Select * From user;
查询的结果(在DataGrip上完成):
id username passw… name last_name type
1 managertest oAWpW… BENJAMIN ARIEL NAVA MARTINEZ 1
2 clerktest iRYMz… EMPLEADO PRUEBA 0
正如您所看到的,记录在那里(我已经验证了查询是在完全相同的文件上执行的),但是,C#程序似乎跳过了if
语句(因为read返回false
)好像数据库中没有行,这里有什么问题?
答案 0 :(得分:0)
致电SQLiteCommand.Prepare
AFTER后您已完成构建命令
//...
string sql = "SELECT * FROM user WHERE username = @username ;";
SQLiteCommand command = new SQLiteCommand(sql, connection);
command.Parameters.AddWithValue("@username", username);
// Call Prepare after setting the Commandtext and Parameters.
command.Prepare();
SQLiteDataReader reader = command.ExecuteReader();
//...