孙世强
2025-11-20 c82db51f2df281afe54c08dd55cb049693e5a889
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace 补片.DAL
{
    public class MySqlSqHelper
    {
        /// <summary>
        /// 连接数据库
        /// </summary>
        /// <param name="databasename"></param>
        /// <returns></returns>
        private static MySqlConnection GetConnection(string databasename, string ip = "")
        {
            try
            {
 
                StringBuilder sb = new StringBuilder();
#if ZYZ
             sb.AppendFormat("server={0};","192.168.74.132");
                sb.AppendFormat("user id={0};", "root");
                sb.AppendFormat("password={0};", "123456");
#else
                sb.AppendFormat("server={0};", ip == "" ? BuPianBll.ServerIP : ip);
                sb.AppendFormat("user id={0};", "root");
                sb.AppendFormat("password={0};", BuPianBll.ServerIP == "127.0.0.1" ? " " : "beibo.123/ ");
#endif
                sb.AppendFormat("persistsecurityinfo={0};", "true");
                sb.AppendFormat("sslmode={0};", "none");
                sb.AppendFormat("database={0};", ip == "" ? "sap" + databasename : databasename);
                MySqlConnection conn = new MySqlConnection(sb.ToString());
                conn.Open();
                return conn;
            }
            catch (MySqlException e)
            {
                //throw new Exception(e.Message);
                gongchenglog.ShowErrorMessage("无法连接到任何指定的MySQL主机。\r\n请检查与MySQL主机网络连接是否正常。\r\n" + e.Message, "数据库连接提示");
                return null;
            }
        }
 
 
 
 
        #region
        /// <summary>
        /// 执行一句SQL
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="databaseName"></param>
        /// <returns></returns>
        public static bool ExecuteSql(string sql, string databaseName)
        {
            try
            {
                using (MySqlConnection connection = GetConnection(databaseName))
                {
                    if (connection == null)
                    {
                        return false;
                    }
                    using (MySqlCommand cmd = new MySqlCommand(sql, connection))
                    {
                        int rows = cmd.ExecuteNonQuery();
                        connection.Close();
                        return rows > 0;
                    }
 
                }
            }
            catch (MySqlException e)
            {
                throw new Exception(e.Message);
            }
        }
        #endregion
 
    }
}