易创云论坛

 找回密码
 立即注册
查看: 3220|回复: 0

使用C#连接、操作MySQL数据库

[复制链接]

170

主题

178

帖子

10万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
100700
发表于 2019-7-7 22:39:45 | 显示全部楼层 |阅读模式
  1. sing System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Windows.Forms;
  5. using System.Diagnostics;
  6. using System.IO;
  7. //Add MySql Library
  8. using MySql.Data.MySqlClient;

  9. namespace ConnectCsharpToMysql
  10. {
  11. class DBConnect
  12. {
  13.     private MySqlConnection connection;
  14.     private string server;
  15.     private string database;
  16.     private string uid;
  17.     private string password;

  18.     //Constructor
  19.     public DBConnect()
  20.     {
  21.         Initialize();
  22.     }

  23.     //Initialize values
  24.     private void Initialize()
  25.     {
  26.         server = "localhost";
  27.         database = "csahrpdb";
  28.         uid = "root";
  29.         //password = "Abcd1234";
  30.         password = "123456";

  31.         string connectionString;
  32.         connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
  33. //server=127.0.0.1;user=root;database=testsql;port=3306;password=root;
  34.         connection = new MySqlConnection(connectionString);
  35.     }


  36.     //open connection to database
  37.     private bool OpenConnection()
  38.     {
  39.         try
  40.         {
  41.             connection.Open();
  42.             return true;
  43.         }
  44.         catch (MySqlException ex)
  45.         {
  46.             //When handling errors, you can your application's response based on the error number.
  47.             //The two most common error numbers when connecting are as follows:
  48.             //0: Cannot connect to server.
  49.             //1045: Invalid user name and/or password.
  50.             switch (ex.Number)
  51.             {
  52.                 case 0:
  53.                     MessageBox.Show("Cannot connect to server.  Contact administrator");
  54.                     break;

  55.                 case 1045:
  56.                     MessageBox.Show("Invalid username/password, please try again");
  57.                     break;
  58.             }
  59.             return false;
  60.         }
  61.     }

  62.     //Close connection
  63.     private bool CloseConnection()
  64.     {
  65.         try
  66.         {
  67.             connection.Close();
  68.             return true;
  69.         }
  70.         catch (MySqlException ex)
  71.         {
  72.             MessageBox.Show(ex.Message);
  73.             return false;
  74.         }
  75.     }

  76.     //Insert statement
  77.     public void Insert()
  78.     {
  79.         string query = "INSERT INTO tableinfo (id,name, age) VALUES('11','John Smith', '33')";

  80.         //open connection
  81.         if (this.OpenConnection() == true)
  82.         {
  83.             //create command and assign the query and connection from the constructor
  84.             MySqlCommand cmd = new MySqlCommand(query, connection);
  85.             
  86.             //Execute command
  87.             cmd.ExecuteNonQuery();

  88.             //close connection
  89.             this.CloseConnection();
  90.         }
  91.     }

  92.     //Update statement
  93.     public void Update()
  94.     {
  95.         string query = "UPDATE tableinfo SET id='22', name='Joe', age='22' WHERE name='John Smith'";

  96.         //Open connection
  97.         if (this.OpenConnection() == true)
  98.         {
  99.             //create mysql command
  100.             MySqlCommand cmd = new MySqlCommand();
  101.             //Assign the query using CommandText
  102.             cmd.CommandText = query;
  103.             //Assign the connection using Connection
  104.             cmd.Connection = connection;

  105.             //Execute query
  106.             cmd.ExecuteNonQuery();

  107.             //close connection
  108.             this.CloseConnection();
  109.         }
  110.     }

  111.     //Delete statement
  112.     public void Delete(int id)
  113.     {
  114.         string query = "DELETE FROM tableinfo WHERE id=" + id;

  115.         if (this.OpenConnection() == true)
  116.         {
  117.             MySqlCommand cmd = new MySqlCommand(query, connection);
  118.             cmd.ExecuteNonQuery();
  119.             this.CloseConnection();
  120.         }
  121.     }
  122.    
  123.     //Select statement
  124.     public List<string>[] Select()
  125.     {
  126.         string query = "SELECT * FROM tableinfo";

  127.         //Create a list to store the result
  128.         List<string>[] list = new List<string>[3];
  129.         list[0] = new List<string>();
  130.         list[1] = new List<string>();
  131.         list[2] = new List<string>();

  132.         //Open connection
  133.         if (this.OpenConnection() == true)
  134.         {
  135.             //Create Command
  136.             MySqlCommand cmd = new MySqlCommand(query, connection);
  137.             //Create a data reader and Execute the command
  138.             MySqlDataReader dataReader = cmd.ExecuteReader();
  139.             
  140.             //Read the data and store them in the list
  141.             while (dataReader.Read())
  142.             {
  143.                 list[0].Add(dataReader["id"] + "");
  144.                 list[1].Add(dataReader["name"] + "");
  145.                 list[2].Add(dataReader["age"] + "");
  146.             }

  147.             //close Data Reader
  148.             dataReader.Close();

  149.             //close Connection
  150.             this.CloseConnection();

  151.             //return list to be displayed
  152.             return list;
  153.         }
  154.         else
  155.         {
  156.             return list;
  157.         }
  158.     }

  159.     //Count statement
  160.     public int Count()
  161.     {
  162.         string query = "SELECT Count(*) FROM tableinfo";
  163.         int Count = -1;

  164.         //Open Connection
  165.         if (this.OpenConnection() == true)
  166.         {
  167.             //Create Mysql Command
  168.             MySqlCommand cmd = new MySqlCommand(query, connection);

  169.             //ExecuteScalar will return one value
  170.             Count = int.Parse(cmd.ExecuteScalar()+"");
  171.             
  172.             //close Connection
  173.             this.CloseConnection();

  174.             return Count;
  175.         }
  176.         else
  177.         {
  178.             return Count;
  179.         }
  180.     }

  181.     //Backup
  182.     public void Backup()
  183.     {
  184.         try
  185.         {
  186.             DateTime Time = DateTime.Now;
  187.             int year = Time.Year;
  188.             int month = Time.Month;
  189.             int day = Time.Day;
  190.             int hour = Time.Hour;
  191.             int minute = Time.Minute;
  192.             int second = Time.Second;
  193.             int millisecond = Time.Millisecond;

  194.             //Save file to C:\ with the current date as a filename
  195.             string path;
  196.             path = "C:\" + year + "-" + month + "-" + day + "-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".sql";
  197.             StreamWriter file = new StreamWriter(path);

  198.             
  199.             ProcessStartInfo psi = new ProcessStartInfo();
  200.             psi.FileName = "mysqldump";
  201.             psi.RedirectStandardInput = false;
  202.             psi.RedirectStandardOutput = true;
  203.             psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}", uid, password, server, database);
  204.             psi.UseShellExecute = false;

  205.             Process process = Process.Start(psi);

  206.             string output;
  207.             output = process.StandardOutput.ReadToEnd();
  208.             file.WriteLine(output);
  209.             process.WaitForExit();
  210.             file.Close();
  211.             process.Close();
  212.         }
  213.         catch (IOException ex)
  214.         {
  215.             MessageBox.Show("Error , unable to backup!");
  216.         }
  217.     }

  218.     //Restore
  219.     public void Restore()
  220.     {
  221.         try
  222.         {
  223.             //Read file from C:\
  224.             string path;
  225.             path = "C:\\MySqlBackup.sql";
  226.             StreamReader file = new StreamReader(path);
  227.             string input = file.ReadToEnd();
  228.             file.Close();


  229.             ProcessStartInfo psi = new ProcessStartInfo();
  230.             psi.FileName = "mysql";
  231.             psi.RedirectStandardInput = true;
  232.             psi.RedirectStandardOutput = false;
  233.             psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}", uid, password, server, database);
  234.             psi.UseShellExecute = false;

  235.             
  236.             Process process = Process.Start(psi);
  237.             process.StandardInput.WriteLine(input);
  238.             process.StandardInput.Close();
  239.             process.WaitForExit();
  240.             process.Close();
  241.         }
  242.         catch (IOException ex)
  243.         {
  244.             MessageBox.Show("Error , unable to Restore!");
  245.         }
  246.     }
  247. } }
复制代码

原文链接:https://www.cnblogs.com/xiebaochun/p/3329625.html




链接: https://pan.baidu.com/s/1vZkBe1tdsQVDxdxdw6dd4A
提取码: zgct
复制这段内容后打开百度网盘手机App,操作更方便哦
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|易创云论坛 ( 吉ICP备17001024号-1 )

GMT+8, 2025-2-2 01:03 , Processed in 0.279054 second(s), 19 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表