C#读写MySql

(1)首先需要下载C#访问MySQL数据库的ADO.NET驱动程序
http://dev.mysql.com/downloads/connector/net/6.0.html


我下载的版本为: mysql-connector-net-6.3.8.msi
http://dev.mysql.com/downloads/mirror.php?id=405442


(2)在应用工程中引用组件MySQL.Data.dll


(3)主要代码和C#操作MySql很类似:

using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using MySql.Data.MySqlClient;

public class UserInfo
{
    public string username { get; set; }
    public string xingming { get; set; }
    public int quanxian { get; set; }
}

public class clsoptuser
{
    public string UserLogin(string strUserName, string strPassword)
    {
        string strResult = "";

        MySqlConnection msqlConnection = null;
        msqlConnection = new MySqlConnection("server=127.0.0.1;user id=root;Password=root;database=car_list;persist security info=False");
        
        MySqlCommand msqlCommand = new MySqlCommand();
        msqlCommand.Connection = msqlConnection;

        //define the command text
        msqlCommand.CommandText = "SELECT * FROM users WHERE username=" + strUserName + " AND password=" + strPassword;
        try
        {
            //open the connection
            msqlConnection.Open();
            
            //use a DataReader to process each record
            MySqlDataReader msqlReader = msqlCommand.ExecuteReader();
            while (msqlReader.Read())
            {
                //do something with each record
                UserInfo u = new UserInfo();
                u.username = msqlReader.GetString(msqlReader.GetOrdinal("username"));
                u.xingming = msqlReader.GetString(msqlReader.GetOrdinal("xingming"));
                u.quanxian = msqlReader.GetInt32(msqlReader.GetOrdinal("quanxian"));

                return ToJSON(u);  
            }

            return strResult;
        }
        catch (Exception er)
        {
            //do something with the exception
            Debug.Write(er.Message);
            return strResult;
        }
        finally
        {
            //always close the connection
            msqlConnection.Close();
        }
    }


    public static string ToJSON(object obj)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        return serializer.Serialize(obj);

    }
}

(4)执行插入或者更新

                String sql = string.Format("INSERT INTO `userlogin` (`user_name`) VALUES ('{0}')",
                    strUserName);
                MySqlCommand sqlInsert = new MySqlCommand(sql, msqlConnection);
                sqlInsert.ExecuteNonQuery();
                sqlInsert.Dispose();


©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页