访问Mysql数据库,连接字符串配置

时间:2022-04-25 04:48:06

Step1:App.config文件里进行配置

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
  <connectionStrings> <add name="Connect" connectionString="server=localhost;user=root;pwd=admin;database=BlackCat"/> </connectionStrings>
</configuration>

Step2:添加引用

访问Mysql数据库,连接字符串配置

 

Step3:使用

 public class MySqlHelp
    {
         public static string connectString = ConfigurationManager.ConnectionStrings["Connect"].ConnectionString.ToString();
        /// <summary>
        /// 执行sql语句返回受影响的行数
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static  int ExecuteSql(string sql)
        {
            int count;
            using (MySqlConnection  con = new MySqlConnection(connectString))
            {
                using (MySqlCommand cmd = new MySqlCommand(sql, con))
                {
                    try
                    {
                        con.Open();
                        count = cmd.ExecuteNonQuery();
                        return count;
                    }
                    catch(MySqlException e)
                    {
                        con.Close();
                        throw e;
                    }
                }
            }
            
        }
}