小结一下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数据的更多相关文章

  1. python连接mysql数据表查询表获取数据导入到txt中

    import pymysql'''连接mysql数据表查询表获取数据导入到txt中'''#查询结果写入数据到txtdef get_loan_number(file_txt): connect = py ...

  2. Java中连接MySql数据库的例子

    Java中连接MySql数据库的例子: package com.joinmysql.demo; import java.sql.DriverManager; import java.sql.Resul ...

  3. django 中连接mysql数据库的操作步骤

    django中连接mysql数据库的操作步骤: 1 settings配置文件中 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mys ...

  4. EF连接MySQL数据Web.Config配置

    EF连接MySQL数据Web.Config配置 <?xml version="1.0" encoding="utf-8"?> <configu ...

  5. Odoo中连接mysql数据库

    how to integrate Odoo with MySQL - Stack Overflowhttps://stackoverflow.com/questions/31959919/how-to ...

  6. Django 3.0 中连接mysql 8.0,可以不使用pymysql ,升级Mysqlclient即可

    python 中,连接mysql一般都推荐用pymysql ,而且在django中,网上的教程都是这么连接mysql的. import pymysql pymysql.install_as_MySQL ...

  7. php通过Mysqli和PDO连接mysql数据详解

    前言 在实际开发中,关于数据库操作类,很少是自己去写,大多是通过一些框架去实现,突然自己去写,还是需要借阅手册之类,于是我觉得有必要去总结一下,php连接mysql的方法,php连接mysql,可以通 ...

  8. 在Django中连接MySQL数据库(Python3)

    我的环境:      python3.6,      Django2.1.5,      MySQL8.0.15,      win10,      PyCharm, 要求:已经安装了MySQL数据库 ...

  9. 在python中连接mysql数据库,并进行增删改查

    数据库在开发过程中是最常见的,基本上在服务端的编程过程中都会使用到,mysql是较常见的一种数据库,这里介绍python如果连接到数据库中,并对数据库进行增删改查. 安装mysql的python扩展 ...

随机推荐

  1. Centos Install Keepalived

    Keepalived简介Keepalived 的作用是检测 web 服务器的状态,如果有一台 web 服务器死机,或工作出现故障,Keepalived 将检测到,并将有故障的 web 服务器从系统中剔 ...

  2. BZOJ1095 [ZJOI2007] Hide 捉迷藏 (括号序列 + 线段树)

    题意 给你一颗有 \(n\) 个点的树 , 共有 \(m\) 次操作 有两种类别qwq 将树上一个点染黑/白; 询问树上最远的两个黑点的距离. \((n \le 200000, m ≤500000)\ ...

  3. Codeforces | CF1029C 【Maximal Intersection】

    论Div3出这样巨水的送分题竟然还没多少人AC(虽说当时我也没A...其实我A了D...逃) 这个题其实一点都不麻烦,排序都可以免掉(如果用\(priority \_ queue\)的话) 先考虑不删 ...

  4. Codeforces | CF1010C 【Border】

    这道题大致题意是给定\(n\)个十进制整数和一个进制数\(k\),可以用无数多个给定的十进制整数,问这些十进制整数的和在模k意义下有多少种不同的结果(\(k\)进制下整数的最后一位就是这个数模\(k\ ...

  5. photoshop学习4

    蒙版 路径学习 一.蒙版 蒙版可以理解为一层在图层上的遮挡布,为什么要将图层遮住呢,有什么好处.好处在于容易编辑. 在一个图层上建立一个蒙版之后,可以用再删掉不需要的部分,从而露出原图层的部分.那么这 ...

  6. debugger

    今天爬取cfda时遇到的困难,一旦开启了调试,就debugger pause, ???还有这种操作 一顿google,百度,解决了这个问题,点一下Deactivate breakPoints,然后点一 ...

  7. CF1131F Asya And Kittens(Kruskal重构树,启发式合并)

    这题难度1700,我感觉又小了…… 这题虽然没几个人是用kruskal重构树的思想做的,但是我是,所以我就放了个kruskal重构树的标签. 题目链接:CF原网 题目大意:有一个长为 $n$ 的排列, ...

  8. 在Vue框架中使用百度地图

    1.首先在index.html中引入百度地图 <script type="text/javascript" src="http://api.map.baidu.co ...

  9. C# winfrom 递归(城市名)

    递归的定以:递归在运行过程中,自己调用自己的过程: List<ChinaStates> list = new ChinaData().SelectAll();//查询所有中国的城市的方法: ...

  10. bzoj2434 阿狸的打字机

    题目链接 思路 可以发现,其实题目中所描述的操作,就是在\(AC\)自动机上走的过程.输出就是打上标记.删除就是返回父亲节点. 然后看询问.每次询问字符串\(x\)在字符串中\(y\)出现的次数.其实 ...