欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#读写MySql教程

程序员文章站 2022-03-09 22:11:14
(1)首先需要下载C#访问MySQL数据库的ADO.NET驱动程序 我下载的版本为: mysql-connector-net-6.3.8.msi (2)在应用工程中引用组件My...

(1)首先需要下载C#访问MySQL数据库的ADO.NET驱动程序

我下载的版本为: mysql-connector-net-6.3.8.msi

(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();