C# 使用Visual Studio C从MS Access检索数据
好的,有点背景。我发现用C编写共享DLL是很困难的,而且这真的不值得费心,因为这只是一个学校的项目,基本上已经完成了,无论如何我还是愿意走这条路 所以我通过这个代码把数据放在MS Access中C# 使用Visual Studio C从MS Access检索数据,c#,ms-access,double,C#,Ms Access,Double,好的,有点背景。我发现用C编写共享DLL是很困难的,而且这真的不值得费心,因为这只是一个学校的项目,基本上已经完成了,无论如何我还是愿意走这条路 所以我通过这个代码把数据放在MS Access中 public void SetBal(double money) { bal = money; //balance equals whatever money that was sent to it string query = "Insert into
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;
}
我无法将查询结果转换为双精度。我不知道代码是否是错的,或者我只是走错了方向。提前感谢。您需要创建/打开连接,然后执行查询。您是为insert做的,现在您需要使用select查询在get方法中创建相同的内容。您需要执行查询,然后将查询结果转换为双精度 您正在强制转换字符串SELECT Users。将用户的钱加倍,而不是查询结果。执行与更新查询相同的操作,但执行reader以获取所有值-。谢谢,我甚至不知道我怎么会没有意识到这一点。谢谢你的回复!嘿,谢谢你的回复,我非常感谢。我有个问题。在尝试之后和捕获之前,我了解一切。你能确切地解释一下发生了什么事吗。谢谢,我只是想更好地理解代码。我添加了一堆注释并简化了一点。希望这能帮助你理解它。
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;
}