Winform中使用Mysql.Data.dll實現連接Mysql數據庫並執行sql語句(排除ddl等非法語句的執行)


場景

Winform中連接Mysql8並查詢表中數據進行顯示:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/120395988

與上面實現的流程類似,怎么在連接mysql的基礎上實現執行查詢、編輯、刪除、插入操作的sql。

但是不能執行"drop", "drop database" , "drop table" , "truncate", "alter","rename" , "create"等這些dll語句。

同上面一樣,項目中引入Mysql.Data.dll依賴並設計窗體布局如下

 

 

 

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。

實現

1、聲明變量獲取數據庫連接的相關參數

 

        string connetStr = String.Empty;
        MySqlConnection mySqlConnection = null;
        String hostaddress = String.Empty;
        String port = String.Empty;
        String databaseName = String.Empty;
        String name = String.Empty;
        String pass = String.Empty;
        private MySqlCommand dbCmd = null;
        private MySqlDataReader dbDataReader = null;

 

2、連接按鈕的點擊事件

        private void button_connect_Click(object sender, EventArgs e)
        {

            hostaddress = this.textBox_host.Text.Trim();
            databaseName = this.textBox_database.Text.Trim();
            name = this.textBox_username.Text.Trim();
            pass = this.textBox_password.Text.Trim();
            port = this.textBox_port.Text.Trim();

            connetStr = "server=" + hostaddress + ";port="+ port+";User Id=" + name + ";password=" + pass + ";database=" + databaseName; //localhost不支持ssl連接時,最后一句一定要加!!!
            mySqlConnection = new MySqlConnection(connetStr);
            try
            {
                mySqlConnection.Open(); //連接數據庫
                MessageBox.Show("數據庫連接成功", "提示", MessageBoxButtons.OK);

            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK);     //顯示錯誤信息
            }
        }

連接數據庫效果

 

2、執行新增、編輯、刪除的sql的按鈕的點擊事件

        private void button_executeSql_Click(object sender, EventArgs e)
        {
            string searchStr = this.textBox_sql.Text.Trim();
            if (String.IsNullOrEmpty(this.textBox_sql.Text))
            {
                MessageBox.Show("執行sql為空");           
            }
            else if (!badaoHelper.checkSql(searchStr))
            {
                MessageBox.Show("執行sql不被允許");
            }
            else if (mySqlConnection.State == ConnectionState.Closed) {
                MessageBox.Show("請先建立數據庫連接");
            }
            else {
                try {
                    dbCmd = new MySqlCommand();
                    dbCmd.CommandText = searchStr;
                    dbCmd.Connection = mySqlConnection;
                    int result = dbCmd.ExecuteNonQuery();
                    if (result > 0)
                    {
                        MessageBox.Show("sql執行成功,數據庫連接關閉,受影響的行數:" + result);
                        mySqlConnection.Close();
                    }
                    else {
                        MessageBox.Show("sql執行失敗,數據庫連接關閉,受影響的行數:" + result);
                        mySqlConnection.Close();
                    }
                }
                catch (Exception ex) {
                    mySqlConnection.Close();
                    MessageBox.Show("sql執行失敗,數據庫連接關閉,報錯信息:" + ex.Message);
                }
              
            }
        }

執行sql的效果

 

 

這其中用到了校驗是否包含指定sql的工具類方法checkSql

        public static bool checkSql(string sql)
        {
            bool isRight = true;
            string[] notAllowKeyWords = { "drop", "drop database" , "drop table" , "truncate", "alter","rename" , "create" };
            for (int i = 0; i < notAllowKeyWords.Length; i++)
            {
                string arr = notAllowKeyWords[i];
                if (sql.ToLower().Contains(arr.ToLower())) {
                    isRight = false;
                }
            }
            return isRight;
        }

3、執行查詢sql的執行按鈕的點擊事件

        private void button_sql_query_Click(object sender, EventArgs e)
        {
            string searchStr = this.textBox_sql_query.Text.Trim();
            if (String.IsNullOrEmpty(searchStr))
            {
                MessageBox.Show("執行sql為空");
            } else if (!badaoHelper.checkSql(searchStr)) {
                MessageBox.Show("執行sql不被允許");
            }
            else if (mySqlConnection.State == ConnectionState.Closed)
            {
                MessageBox.Show("請先建立數據庫連接");
            }
            else
            {
                try
                {
                  
                    MySqlDataAdapter adapter = new MySqlDataAdapter(searchStr, mySqlConnection);
                    DataSet dataSet = new DataSet();
                    adapter.Fill(dataSet, "table1");
                    this.dataGridView_select.DataSource = dataSet.Tables["table1"];
                }
                catch (Exception ex)
                {
                    MessageBox.Show("報錯信息:" + ex.Message);
                }

            }
        }

執行查詢sql的效果

 

 

4、完整示例代碼

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BdtdDataUpload
{
    public partial class Main : Form
    {
        string connetStr = String.Empty;
        MySqlConnection mySqlConnection = null;
        String hostaddress = String.Empty;
        String port = String.Empty;
        String databaseName = String.Empty;
        String name = String.Empty;
        String pass = String.Empty;
        private MySqlCommand dbCmd = null;
        private MySqlDataReader dbDataReader = null;
        public Main()
        {
            InitializeComponent();
        }

        private void button_connect_Click(object sender, EventArgs e)
        {

            hostaddress = this.textBox_host.Text.Trim();
            databaseName = this.textBox_database.Text.Trim();
            name = this.textBox_username.Text.Trim();
            pass = this.textBox_password.Text.Trim();
            port = this.textBox_port.Text.Trim();

            connetStr = "server=" + hostaddress + ";port="+ port+";User Id=" + name + ";password=" + pass + ";database=" + databaseName; //localhost不支持ssl連接時,最后一句一定要加!!!
            mySqlConnection = new MySqlConnection(connetStr);
            try
            {
                mySqlConnection.Open(); //連接數據庫
                MessageBox.Show("數據庫連接成功", "提示", MessageBoxButtons.OK);

            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK);     //顯示錯誤信息
            }
        }

        private void button_disconnect_Click(object sender, EventArgs e)
        {
            if (mySqlConnection.State == ConnectionState.Open) {
                mySqlConnection.Close();
            }
           
        }

        private void button_executeSql_Click(object sender, EventArgs e)
        {
            string searchStr = this.textBox_sql.Text.Trim();
            if (String.IsNullOrEmpty(this.textBox_sql.Text))
            {
                MessageBox.Show("執行sql為空");           
            }
            else if (!badaoHelper.checkSql(searchStr))
            {
                MessageBox.Show("執行sql不被允許");
            }
            else if (mySqlConnection.State == ConnectionState.Closed) {
                MessageBox.Show("請先建立數據庫連接");
            }
            else {
                try {
                    dbCmd = new MySqlCommand();
                    dbCmd.CommandText = searchStr;
                    dbCmd.Connection = mySqlConnection;
                    int result = dbCmd.ExecuteNonQuery();
                    if (result > 0)
                    {
                        MessageBox.Show("sql執行成功,數據庫連接關閉,受影響的行數:" + result);
                        mySqlConnection.Close();
                    }
                    else {
                        MessageBox.Show("sql執行失敗,數據庫連接關閉,受影響的行數:" + result);
                        mySqlConnection.Close();
                    }
                }
                catch (Exception ex) {
                    mySqlConnection.Close();
                    MessageBox.Show("sql執行失敗,數據庫連接關閉,報錯信息:" + ex.Message);
                }
              
            }
        }

        private void button_sql_query_Click(object sender, EventArgs e)
        {
            string searchStr = this.textBox_sql_query.Text.Trim();
            if (String.IsNullOrEmpty(searchStr))
            {
                MessageBox.Show("執行sql為空");
            } else if (!badaoHelper.checkSql(searchStr)) {
                MessageBox.Show("執行sql不被允許");
            }
            else if (mySqlConnection.State == ConnectionState.Closed)
            {
                MessageBox.Show("請先建立數據庫連接");
            }
            else
            {
                try
                {
                  
                    MySqlDataAdapter adapter = new MySqlDataAdapter(searchStr, mySqlConnection);
                    DataSet dataSet = new DataSet();
                    adapter.Fill(dataSet, "table1");
                    this.dataGridView_select.DataSource = dataSet.Tables["table1"];
                }
                catch (Exception ex)
                {
                    MessageBox.Show("報錯信息:" + ex.Message);
                }

            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM