使用 Visual Studio C# 从 MS Access 检索数据
本文关键字:Access 检索 数据 MS Visual Studio 使用 | 更新日期: 2023-09-27 18:31:24
好的,所以有点背景。我发现在 C# 中做一个共享 DLL 很困难,而且真的不值得麻烦,因为这只是一个几乎完成的学校项目,无论如何我宁愿走这条路。
所以我通过这段代码将数据放在MS Access中。
public void SetBal(double money)
{
bal = money; //balance equals whatever money that was sent to it
string query = "Insert into Users" + "([Money])" + "Values (@Money)" + "where Users.UserID = 1";
dbconn = new OleDbConnection(connection);
OleDbCommand insert = new OleDbCommand(query, dbconn);
insert.Parameters.Add("Money", OleDbType.Char).Value = bal;
dbconn.Open();
try
{
int count = insert.ExecuteNonQuery();
}
catch (OleDbException ex)
{
}
finally
{
dbconn.Close();
}
}
好吧,这行得通。问题是当我尝试从数据库中检索数据时。
public double GetBal()
{
string query = "SELECT Users.Money FROM Users";
bal = Convert.ToDouble(query);
return bal;
}
我无法将查询结果转换为双精度值。我不知道代码是错误的,还是我只是以错误的方式去做。提前谢谢。
public double GetBal()
{
// Make sure you change this to a real userID that you pass in.
var query = "SELECT Users.Money FROM Users WHERE Users.UserID = 1";
double balance = 0;
using (var dbconn = new OleDbConnection(connectionString)) {
var command = new OleDbCommand(query, dbconn);
dbconn.Open();
// Send the command (query) to the connection, creating an
// OleDbReader in the process. We want it to close the database
// connection in the process so we pass in that behavior as an
// argument (CommandBehavior.CloseConnection)
var myReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// this while loop will keep executing until there are no more rows
// to read from the database. myReader.Read() moves to the next row
// in the database too. The first read() puts you at the first row.
while(myReader.Read())
{
// Use the reader's GetDouble() method to read the data and convert
// it to a double. The 0 is there because it is the first column in
// the results. for example to read the third column, it would be
// myReader.GetDouble(2).
balance = myReader.GetDouble(0));
}
// because there is only one row (query said where Users.UserID = 1) the
// above loop will only execute once.
// Close the reader so we can tell the command that the connection
// can be closed...because CommandBehavior.CloseConnection was specified
myReader.Close();
}
// return the value we got from the database
return balance;
}
您需要创建/打开连接,然后执行查询。 您为插入做了此操作 - 现在您需要使用选择查询在 get 方法中创建相同的内容。 您需要执行查询,然后将查询结果转换为双精度值。