Guest User

Untitled

a guest
Nov 21st, 2018
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. using System;
  2. using MySql.Data.MySqlClient;
  3.  
  4. namespace insert
  5. {
  6. public class User
  7. {
  8. public string ID;
  9. public string Name;
  10. public string Pass;
  11. public int Age;
  12.  
  13. public User(string id, string name, string pass, int age)
  14. {
  15. if (id.Length > 5 || name.Length > 20 || pass.Length > 3)
  16. throw new FormatException("Illegal Format.");
  17. ID = id;
  18. Name = name;
  19. Pass = pass;
  20. Age = age;
  21. }
  22. }
  23.  
  24. public partial class _Default : System.Web.UI.Page
  25. {
  26. private int Insert(User user)
  27. {
  28. string connectionInfo = string.Format("server={0};user id={1};password={2};database={3};charset=utf8;",
  29. "localhost", "root", "", "wp22");
  30. using (var connection = new MySqlConnection(connectionInfo))
  31. {
  32. connection.Open();
  33. var command = new MySqlCommand("Insert Into user (id, name, pass, age) Values (?ID, ?NAME, ?PASS, ?AGE);", connection);
  34. command.Parameters.AddWithValue("?ID", user.ID);
  35. command.Parameters.AddWithValue("?NAME", user.Name);
  36. command.Parameters.AddWithValue("?PASS", user.Pass);
  37. command.Parameters.AddWithValue("?AGE", user.Age);
  38. return command.ExecuteNonQuery();
  39. }
  40. }
  41.  
  42. protected void Page_Load(object sender, EventArgs e) { }
  43.  
  44. protected void ButtonInsert_Click(object sender, EventArgs e)
  45. {
  46. int age;
  47. try
  48. {
  49. if (!int.TryParse(TextBoxAge.Text, out age)) throw new FormatException("Invalid Age Format.");
  50. var user = new User(TextBoxID.Text, TextBoxName.Text, TextBoxPass.Text, age);
  51. Insert(user);
  52. LabelResult.Text = "OK";
  53. }
  54. catch (FormatException err)
  55. {
  56. LabelResult.Text = string.Format("Canceled ({0})", err.Message);
  57. }
  58. }
  59. }
  60. }
Add Comment
Please, Sign In to add comment