C#中连接MySQL数据
小结一下MySQL在C#中是如何连接的,并做一些简单的选择(SELECT)、插入( INSERT)、更新( UPDATE)、删除(DELETE )
(一)连接
a) Firstly, you should install MySQL. To use the methods in the MySQL Connector/NET you should add a reference to it. Right click your project in the Solution Explorer and click Add Reference… In the .NET tab, chose MySql.Data and click ok.
b) In your code, you should add the line using MySql.Data.MySqlClient; in order to be able to use methods for accessing MySql.
using MySql.Data.MySqlClient;
c) To Connect to a MySql Database:
String str = @"server=localhost;database=yourDBname;userid=root;password=yourDBpassword;";
MySqlConnection con = null;
try
{
con = new MySqlConnection(str);
con.Open(); //open the connection
}
catch (MySqlException err) //We will capture and display any MySql errors that will occur
{
Console.WriteLine("Error: " + err.ToString());
}
finally
{
if (con != null)
{
con.Close(); //safely close the connection
}
} //remember to safely close the connection after accessing the database
localhost是服务器地址。
(二)其他操作
a) 执行已准备的一些MySQL指令To code some MySQL commands using Prepared Statements:
String str = @"server=localhost;database=yourDBname;userid=root;password=yourDBpassword;";
MySqlConnection con = null;
try
{
con = new MySqlConnection(str);
con.Open(); //open the connection
//This is the mysql command that we will query into the db.
//It uses Prepared statements and the Placeholder is @name.
//Using prepared statements is faster and secure.
String cmdText = "INSERT INTO myTable(name) VALUES(@name)";
MySqlCommand cmd = new MySqlCommand(cmdText,con);
cmd.Prepare();
//we will bound a value to the placeholder
cmd.Parameters.AddWithValue("@name", "your value here");
cmd.ExecuteNonQuery(); //execute the mysql command
}
catch (MySqlException err)
{
Console.WriteLine("Error: " + err.ToString());
}
finally
{
if (con != null)
{
con.Close(); //close the connection
}
} //remember to close the connection after accessing the database
*Note: You can also try this kind of cmdText, “INSERT INTO myTable VALUES(@name,@age,@contact)”;
Then add the cmd.Parameters.AddWithValue for each placeholder @name,@age,@contact.
If you don't want a column in your table to be bypassed you may use NULL. e.g. “INSERT INTO myTable VALUES(NULL,@name,@age,@contact)”;
b) 使用MySqlDataReader检索数据To Retrieve Data using MySqlDataReader:
String str = @"server=localhost;database=yourDBname;userid=root;password=yourDBpassword;";
MySqlConnection con = null;
//MySqlDataReader Object
MySqlDataReader reader = null;
try
{
con = new MySqlConnection(str);
con.Open(); //open the connection
//We will need to SELECT all or some columns in the table
//via this command
String cmdText = "SELECT * FROM myTable";
MySqlCommand cmd = new MySqlCommand(cmdText,con);
reader = cmd.ExecuteReader(); //execure the reader
/*The Read() method points to the next record It return false if there are no more records else returns true.*/
while (reader.Read())
{
/*reader.GetString(0) will get the value of the first column of the table myTable because we selected all columns using SELECT * (all); the first loop of the while loop is the first row; the next loop will be the second row and so on...*/
Console.WriteLine(reader.GetString());
}
}
catch (MySqlException err)
{
Console.WriteLine("Error: " + err.ToString());
}
finally
{
if (reader != null)
{
reader.Close();
}
if (con != null)
{
con.Close(); //close the connection
}
} //remember to close the connection after accessing the database
c) 执行某一些SQL语句To Execute Some MySql Statements:
SELECT:
//This is the simple code of executing MySql Commands in C#
String cmdText = "SELECT id,name,contact FROM myTable"; //This line is the MySql Command
MySqlCommand cmd = new MySqlCommand(cmdText, con);
cmd.ExecuteNonQuery(); //Execute the command
UPDATE:
//example on how to use UPDATE
cmd = new MySqlCommand("UPDATE ab_data SET banned_from='" + from + "' , banned_until='" + until + "' WHERE name='" + name + "'", con);
cmd.ExecuteNonQuery();
DELETE:
//example on how to use DELETE
cmd = new MySqlCommand("DELETE FROM tbName WHERE colName = someValue",con);
cmd.ExecuteNonQuery();
注:在使用数据库前,必须要确保MySQL数据库服务已经打开(通过con.Open()),并一定要安全地关闭(con.Close())。
Adjusted from : http://forum.codecall.net/topic/71422-connecting-to-a-mysql-database-in-c/
C#中连接MySQL数据的更多相关文章
- python连接mysql数据表查询表获取数据导入到txt中
import pymysql'''连接mysql数据表查询表获取数据导入到txt中'''#查询结果写入数据到txtdef get_loan_number(file_txt): connect = py ...
- Java中连接MySql数据库的例子
Java中连接MySql数据库的例子: package com.joinmysql.demo; import java.sql.DriverManager; import java.sql.Resul ...
- django 中连接mysql数据库的操作步骤
django中连接mysql数据库的操作步骤: 1 settings配置文件中 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mys ...
- EF连接MySQL数据Web.Config配置
EF连接MySQL数据Web.Config配置 <?xml version="1.0" encoding="utf-8"?> <configu ...
- Odoo中连接mysql数据库
how to integrate Odoo with MySQL - Stack Overflowhttps://stackoverflow.com/questions/31959919/how-to ...
- Django 3.0 中连接mysql 8.0,可以不使用pymysql ,升级Mysqlclient即可
python 中,连接mysql一般都推荐用pymysql ,而且在django中,网上的教程都是这么连接mysql的. import pymysql pymysql.install_as_MySQL ...
- php通过Mysqli和PDO连接mysql数据详解
前言 在实际开发中,关于数据库操作类,很少是自己去写,大多是通过一些框架去实现,突然自己去写,还是需要借阅手册之类,于是我觉得有必要去总结一下,php连接mysql的方法,php连接mysql,可以通 ...
- 在Django中连接MySQL数据库(Python3)
我的环境: python3.6, Django2.1.5, MySQL8.0.15, win10, PyCharm, 要求:已经安装了MySQL数据库 ...
- 在python中连接mysql数据库,并进行增删改查
数据库在开发过程中是最常见的,基本上在服务端的编程过程中都会使用到,mysql是较常见的一种数据库,这里介绍python如果连接到数据库中,并对数据库进行增删改查. 安装mysql的python扩展 ...
随机推荐
- 【BZOJ5336】[TJOI2018]party(动态规划)
[BZOJ5336][TJOI2018]party(动态规划) 题面 BZOJ 洛谷 题解 这题好神仙啊... 考虑普通的\(LCS\)的\(dp\),\(f[i][j]=\max\{f[i-1][j ...
- 【BZOJ5322】[JXOI2018]排序问题(模拟)
[BZOJ5322][JXOI2018]排序问题(模拟) 题面 BZOJ 洛谷 题解 这题就显得很呆. 显然就是每次找到\([l,r]\)中出现次数最小的那个数并且放一个. 然后随便模拟一下就好了Qw ...
- luogu4159 迷路 (矩阵加速)
考虑如果只有距离为1的边,那我用在时间i到达某个点的状态数矩阵 乘上转移矩阵(就是边的邻接矩阵),就能得到i+1时间的 然后又考虑到边权只有1~9,那可以把边拆成只有距离为1的 具体做法是一个点拆成9 ...
- 8、16、32-BIT系列单片机区别与特点
一.8位单片机 8031/8051/8751是Intel公司早期的产品 1.8031的特点 8031片内不带程序存储器ROM,使用时用户需外接程序存储器和一片逻辑电路373,外接的程序存储器多为EPR ...
- Spring 整合 Hibernate 时启用二级缓存实例详解
写在前面: 1. 本例使用 Hibernate3 + Spring3: 2. 本例的查询使用了 HibernateTemplate: 1. 导入 ehcache-x.x.x.jar 包: 2. 在 a ...
- 洛谷P2375 动物园
我要死了.这是我做过的最恶心的题之一. 天下第一的大毒瘤.有gay毒. 我不如熊猫好多年... 题意:给定字符串,求g[i],表示:[0, i]中满足该子串既是前缀又是后缀还不重叠的子串数. 解:题面 ...
- 把axios封装为vue插件使用
前言 自从Vue2.0推荐大家使用 axios 开始,axios 被越来越多的人所了解.使用axios发起一个请求对大家来说是比较简单的事情,但是axios没有进行封装复用,项目越来越大,引起的代码冗 ...
- js或jQuery获取当前屏幕的各种高度
Javascript: 网页可见区域宽: document.body.clientWidth网页可见区域高: document.body.clientHeight网页可见区域宽: document.b ...
- No cached version of cn.lightsky.infiniteindicator:library:1.2.2 available for offline mode.
去掉勾勾
- hystrix项目实战
闲话少说: 总共分6步: (1)添加hystrix依赖以及监控的依赖 <dependency> <groupId>org.springframework.cloud</g ...