1

好了,说点背景吧。我发现用 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;
    }

我无法将查询结果转换为双精度。我不知道代码是否只是错误的,或者我只是以错误的方式去做。提前致谢。

4

2 回答 2

2
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;
}
于 2012-04-17T04:03:51.143 回答
0

您需要创建/打开您的连接,然后执行查询。您为插入完成了它 - 现在您需要使用选择查询在 get 方法中创建相同的内容。您需要执行查询,然后将查询结果转换为双精度。

于 2012-04-17T03:48:28.250 回答