0

我有一个乐透抽奖方法,它应该从购买的彩票数据库中找到中奖彩票。但我无法显示查询结果。(我知道这不是乐透的真正运作方式,我稍后会随机化数字:P)

绘制.aspx.cs

public void LottoDraw(object sender, EventArgs e)
{
    var connectionstring = "Server=C;Database=lotto;User Id=lottoadmin;Password=password;";

    using (var con = new SqlConnection(connectionstring))  // Create connection with automatic disposal
    {
        con.Open();

        using (var tran = con.BeginTransaction())  // Open a transaction
        {
            // Create command with parameters
            string sql =
                "SELECT TOP 1 * FROM tblLotto ORDER BY NEWID()";
            var cmd = new SqlCommand(sql, con);

            cmd.Transaction = tran;
            cmd.ExecuteNonQuery(); // Execute the query

            tran.Commit();  // commit transaction

            Response.Write("<br />");
            Response.Write("<br />");
            Response.Write("end...");
        }
    }
}
4

1 回答 1

1

这是因为您使用的是执行非查询。

要检索结果,您需要使用 SQLReader 或 SqlDataAdapter

我个人发现使用 DataAdapter 更容易:

    DataTable t = new DataTable();

    using (SqlConnection c = new SqlConnection(DataConnectionString))
    {
         c.Open();
         // Create new DataAdapter
         using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM EmployeeIDs", c))     
         {
              // Use DataAdapter to fill DataTable
              a.Fill(t);
         }
    }

然后,您可以通过以下方式访问您的数据:

 if(t.Rows.Count == 1){

      String val0 = t.Rows[0]["VAL0"].ToString();
      String val1 = t.Rows[0]["VAL1"].ToString();
      String val2 = t.Rows[0]["VAL2"].ToString();
      String val3 = t.Rows[0]["VAL3"].ToString();
      String val4 = t.Rows[0]["VAL4"].ToString();
      String val5 = t.Rows[0]["VAL5"].ToString();
 }
于 2013-06-23T10:40:28.697 回答