AdoNetMySqlController.cs 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Data.Common;
  5. using System.Threading.Tasks;
  6. using System.Web.Mvc;
  7. using MySql.Data.MySqlClient;
  8. using Benchmarks.Mono.AspNet.Models;
  9. namespace Benchmarks.Mono.AspNet.Controllers
  10. {
  11. public class AdoNetMySqlController : Controller
  12. {
  13. static Random random = new Random();
  14. static string connectionString = ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString;
  15. public ActionResult Index(int? queries)
  16. {
  17. List<World> worlds = new List<World>();
  18. using (MySqlConnection connection = new MySqlConnection(connectionString))
  19. {
  20. connection.Open();
  21. using (MySqlCommand command = new MySqlCommand("SELECT * FROM World WHERE id = @ID", connection))
  22. {
  23. for (int i = 0; i < (queries ?? 1); i++)
  24. {
  25. int randomID = random.Next(0, 10000) + 1;
  26. command.Parameters.Clear();
  27. command.Parameters.AddWithValue("@ID", randomID);
  28. using (DbDataReader reader = command.ExecuteReader())
  29. {
  30. if (reader.Read())
  31. {
  32. World world = new World();
  33. world.id = reader.GetInt32(0);
  34. world.randomNumber = reader.GetInt32(1);
  35. worlds.Add(world);
  36. }
  37. }
  38. }
  39. }
  40. }
  41. return queries != null ? Json(worlds, JsonRequestBehavior.AllowGet)
  42. : Json(worlds[0], JsonRequestBehavior.AllowGet);
  43. }
  44. public async Task<ActionResult> Async(int? queries)
  45. {
  46. List<World> worlds = new List<World>();
  47. using (MySqlConnection connection = new MySqlConnection(connectionString))
  48. {
  49. await connection.OpenAsync();
  50. using (MySqlCommand command = new MySqlCommand("SELECT * FROM World WHERE id = @ID", connection))
  51. {
  52. for (int i = 0; i < (queries ?? 1); i++)
  53. {
  54. int randomID = random.Next(0, 10000) + 1;
  55. command.Parameters.Clear();
  56. command.Parameters.AddWithValue("@ID", randomID);
  57. using (DbDataReader reader = await command.ExecuteReaderAsync())
  58. {
  59. if (await reader.ReadAsync())
  60. {
  61. World world = new World();
  62. world.id = reader.GetInt32(0);
  63. world.randomNumber = reader.GetInt32(1);
  64. worlds.Add(world);
  65. }
  66. }
  67. }
  68. }
  69. }
  70. return queries != null ? Json(worlds, JsonRequestBehavior.AllowGet)
  71. : Json(worlds[0], JsonRequestBehavior.AllowGet);
  72. }
  73. }
  74. }