Form1.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Data.SqlClient;
  6. using System.Drawing;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Windows.Forms;
  11. using MySql.Data.MySqlClient;
  12. namespace WindowsFormsSqlConnectionClose
  13. {
  14. public partial class Form1 : Form
  15. {
  16. public Form1()
  17. {
  18. InitializeComponent();
  19. }
  20. MySqlConnection conn;
  21. private void button1_Click(object sender, EventArgs e)
  22. {
  23. if (textBox1.Text == "")
  24. {
  25. MessageBox.Show("请输入数据库名称");
  26. }
  27. else
  28. {
  29. try
  30. {
  31. string str = "server=localhost;database=" + textBox1.Text.Trim() + ";uid=root;pwd=abc123";
  32. conn = new MySqlConnection(str);
  33. conn.Open();
  34. if (conn.State == ConnectionState.Open)
  35. {
  36. MessageBox.Show("连接成功");
  37. }
  38. }
  39. catch (Exception ex)
  40. {
  41. MessageBox.Show(ex.Message);
  42. textBox1.Text = "";
  43. }
  44. }
  45. }
  46. private void button2_Click(object sender, EventArgs e)
  47. {
  48. try
  49. {
  50. string str = "";
  51. conn.Close();
  52. if (conn.State == ConnectionState.Closed)
  53. {
  54. str = "数据库已经成功关闭\n";
  55. }
  56. conn.Open();
  57. if (conn.State == ConnectionState.Open)
  58. {
  59. str += "数据库已经成功打开\n";
  60. }
  61. richTextBox1.Text = str;
  62. }
  63. catch (Exception ex)
  64. {
  65. richTextBox1.Text = ex.Message;
  66. }
  67. }
  68. private void button3_Click(object sender, EventArgs e)
  69. {
  70. try
  71. {
  72. conn.Dispose();
  73. conn.Open();
  74. }
  75. catch (Exception ex)
  76. {
  77. richTextBox1.Text = ex.Message;
  78. }
  79. }
  80. }
  81. }