码迷,mamicode.com
首页 > 数据库 > 详细

C# MySqlHelper

时间:2015-12-05 17:44:08      阅读:851      评论:0      收藏:0      [点我收藏+]

标签:

1、MySql官方提供ADO.NET访问模式的MySql.Data.dll,下载地址:http://dev.mysql.com/downloads/connector/net/

2、MySqlHelper,如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using MySql.Data.MySqlClient;

namespace drWm.mdal
{
    public class MySqlHelper
    {
        //private static string connstr = @"server=localhost;uid=root;pwd=121535;database=tem;charset=utf8";
        private static string connstr = @"Host=127.0.0.1;UserName=root;Password=xxxx;Database=xxxx;Port=3406;CharSet=utf8;Allow Zero Datetime=true";

        /// <summary>
        /// 执行sql
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int ExecuteSql(string sql)
        {
            using (MySqlConnection conn = new MySqlConnection(connstr))
            {
                using (MySqlCommand cmd = new MySqlCommand(sql, conn))
                {
                    try
                    {
                        conn.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (MySql.Data.MySqlClient.MySqlException e)
                    {
                        conn.Close();
                        throw e;
                    }
                    finally
                    {
                        cmd.Dispose();
                        conn.Close();
                    }
                }
            }
        }

        /// <summary>
        ///  执行查询语句,返回DataSet
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="connstr"></param>
        /// <returns></returns>
        public static DataSet GetDataSet(string sql)
        {
            using (MySqlConnection conn = new MySqlConnection(connstr))
            {
                DataSet ds = new DataSet();
                try
                {
                    conn.Open();
                    MySqlDataAdapter DataAdapter = new MySqlDataAdapter(sql, conn);
                    DataAdapter.Fill(ds);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    conn.Close();
                }
                return ds;
            }
        }

    }
}

 

C# MySqlHelper

标签:

原文地址:http://www.cnblogs.com/bmbh/p/5021744.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!