日期:2014-05-16  浏览次数:20497 次

C#连接Mysql数据库
今天找了好久,悲剧,
给一个例子,和这个DLL文件以及API
private void ExecuteSql(string sql)
        {
            MySqlConnection conn = null;
            MySqlCommand command = null;
            MySqlDataReader reader = null;
            try
            {
                conn = new MySqlConnection(Server=localhost;User Id=root;Password=root;Persist Security Info=True;Database=DataBaseName);
                command = conn.CreateCommand();
                command.CommandText = sql;
                conn.Open();
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(reader[0]);
                    Console.WriteLine(reader[1]);
                    Console.WriteLine(reader[2]);
                }
            }
            catch (MySqlException se)
            {
                Console.WriteLine(Database operation errors :  + se.StackTrace);
            }
            finally
            {
                CloseAll(reader,conn);
            }
        }

        public void CloseAll(MySqlDataReader reader, MySqlConnection conn)
        {
            try
            {
                if (reader != null&&!reader.IsClosed)
                {
                    reader.Close();
                }
                if (conn != null && conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
            catch (Exception)
            {
                
                throw;
            }
        }


上面的部分COPY了别人的。
自己理解之后就记录下来了,因为一般情况下和SQLSERVER连接的比较多,但是和SQL连接也要懂一点