Form1.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 WindowsFormsSqlConnection
  13. {
  14. public partial class Form1 : Form
  15. {
  16. public Form1()
  17. {
  18. InitializeComponent();
  19. }
  20. private void button1_Click(object sender, EventArgs e)
  21. {
  22. if (textBox1.Text == "")
  23. {
  24. MessageBox.Show("请输入要连接的数据库名称");
  25. }
  26. else
  27. {
  28. try
  29. {
  30. string ConStr = "server=localhost;database=" + textBox1.Text.Trim() + ";uid=root;pwd=abc123";
  31. //创建数据库连接对象
  32. //SqlConnection conn = new SqlConnection(ConStr);
  33. MySqlConnection conn = new MySqlConnection(ConStr);
  34. conn.Open();//通过Open方法打开数据库连接
  35. if (conn.State == ConnectionState.Open)
  36. {
  37. label2.Text = "数据库【" + textBox1.Text.Trim() + "】已经连接并打开";
  38. }
  39. }
  40. catch
  41. {
  42. MessageBox.Show("连接数据库失败");
  43. }
  44. }
  45. }
  46. }
  47. }