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();
上一篇: 中国药科大学深度解析:含院校档次级别介绍
下一篇: Spark pagerank
推荐阅读
-
MySQL索引及优化实战教程
-
win10下mysql 5.7.23 winx64安装配置方法图文教程
-
Windows 8下MySQL Community Server 5.6安装配置方法图文教程
-
Windows10下mysql 5.7.21 Installer版安装图文教程
-
mysql5.7.20 安装配置方法图文教程(win10)
-
mysql 5.7.21 winx64绿色版安装配置方法图文教程
-
Windows8下mysql 5.6.15 安装配置方法图文教程
-
Windows10下mysql 8.0.12 解压版安装图文教程
-
mysql server 5.7.20 安装配置方法图文教程
-
mysql 8.0.11 MSI版安装配置图文教程