C#读写MySql教程
程序员文章站
2022-06-23 16:16:11
(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();
推荐阅读
-
mysql 5.7以上版本安装配置方法图文教程(mysql 5.7.12mysql 5.7.13mysql 5.7.14)
-
Mysql5.7.17 winx64.zip解压缩版安装配置图文教程
-
windows系统mysql5.7.18安装图文教程
-
CentOS 7.0如何启动多个MySQL实例教程(mysql-5.7.21)
-
Windows(x86,64bit)升级MySQL 5.7.17免安装版的详细教程
-
mysql 读写分离(基础篇)
-
C#读写操作app.config中的数据应用介绍
-
Windows10下mysql 5.7.17 安装配置方法图文教程
-
MySql 5.6.35 winx64 安装详细教程
-
mysql 5.7.13 安装配置方法图文教程(win10 64位)