设为首页 加入收藏

TOP

C#读写MySql教程
2018-01-16 14:49:50 】 浏览:98
Tags:读写 MySql 教程

(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 java scriptSerializer();  
        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();  
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇MySQL怎么查看所有用户? 下一篇Windows系统下MySQL的下载、安装..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目