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;
    }

クエリ結果を double に変換できません。コードが間違っているだけなのか、単に間違った方法で処理しているだけなのかはわかりません。前もって感謝します。

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

接続を作成/開き、クエリを実行する必要があります。挿入のためにそれを行いました-今度は、select クエリを使用して get メソッドで同じものを作成する必要があります。クエリを実行してから、クエリの結果を double としてキャストする必要があります。

于 2012-04-17T03:48:28.250 に答える