C#--如何连接MySQL

using System;
using System.Collections;
using System.Configuration;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Data;
namespace Sql
//数据库简单测试    
{  
    class InsertSql1
    {
        /// <summary>
        /// @aurhor ZJC
        ///  //简单的demo实现与Mysql数据库的连接、数据插入(查找删除等类似)
        /// </summary>
        /// <param name="args"></param>
         static void Main(string[] args)
        {
            Console.WriteLine(".....................");
            string constr = "server=localhost;User Id=root;password=643872dx;Database=test_navi";
            try
            {
                Console.WriteLine(".....................");
                MySqlConnection mycon = new MySqlConnection(constr);
                mycon.Open();
                Console.WriteLine("Open successed !");
                    
                //这里面输入的其实就是SQL语句罢了!
                ///insert the data                                               
                MySqlCommand mycmd = new MySqlCommand("insert into PlayerInfo(player_nick,player_lv,player_sex,creature_sort,attack,protect,speed) values('5','8','11','4','5','6','7')", mycon);
                if (mycmd.ExecuteNonQuery() > 0)
                {
                    Console.WriteLine("数据插入成功!");
                }                 
                ///modify the data
                /*
                MySqlCommand modify = new MySqlCommand("update PlayerInfo set attack = '28374',protect = '50000',speed = '30' where player_nick = '5'", mycon);
                if (modify.ExecuteNonQuery() > 0)
                {
                    Console.WriteLine("修改成功!");
                }
                 * */
                ///delete the data
             /*   MySqlCommand delete = new MySqlCommand("delete from PlayerInfo where player_nick = '5'",mycon);
                if (delete.ExecuteNonQuery() > 0)
                {
                    Console.WriteLine("数据删除成功!");
                }
              * */
                ///reseach the data
                ////
                /*MySqlCommand research = new MySqlCommand("select player_nick from PlayerInfo where attack > 7000",mycon);
                Console.WriteLine(research.ExecuteScalar());    //输出了信息!
                 * */
                MySqlCommand haha = new MySqlCommand("show databases",mycon);
                Console.WriteLine(haha.ExecuteReader());
                /*
                if (research.ExecuteNonQuery() > 0)
                {
                    Console.WriteLine("查询成功!");
                }*/
                mycon.Close();      //must do this step!do not forget !!
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.ReadLine();
        }
    }
}

C#--如何连接MySQL_第1张图片



注意:Apache一定要设置开机启动,否则连接不会成功。

推荐使用navicat对MySQL进行操作,非常方便!

你可能感兴趣的:(.net,数据库,mysql,C#)