小结一下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. 各种反演细节梳理&模板

    炫酷反演魔术课件byVFK stO FDF Orz(证明全有%%%) 莫比乌斯反演 \(F(n)=\sum\limits_{d|n}f(d)\Rightarrow f(n)=\sum\limits_{ ...

  2. JVM垃圾收集(Java Garbage Collection / Java GC)

    JVM垃圾收集(Java Garbage Collection / Java GC) Java7 Java8 JDK1.8之后将最初的永久代取消了,由元空间取代. 堆内存调优简介 public sta ...

  3. Leetcode 80.删除排序数组中的重复项 II By Python

    给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度. 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成. 示例 ...

  4. [luogu1337][bzoj3680][JSOI2004]平衡点 / 吊打XXX【模拟退火】

    题目描述 gty又虐了一场比赛,被虐的蒟蒻们决定吊打gty.gty见大势不好机智的分出了n个分身,但还是被人多势众的蒟蒻抓住了.蒟蒻们将n个gty吊在n根绳子上,每根绳子穿过天台的一个洞.这n根绳子有 ...

  5. cf1088D Ehab and another another xor problem (构造)

    题意:有两数a,b,每次你可以给定c,d询问a xor c和b xor d的大小关系,最多询问62次($a,b<=2^{30}$),问a和b 考虑从高位往低位做,正在做第i位,已经知道了a和b的 ...

  6. 洛谷P2468 SDOI 2010 粟粟的书架

    题意:给你一个矩形书架,每个点是这本书的页数,每次询问(x1,y1)(x2,y2)这个小矩形里最少需要取几本书使得页数和等于Hi. 题解:小数据二位前缀和预处理+二分答案,大数据一行所以用主席树做,感 ...

  7. 移动端利用-webkit-box水平垂直居中(旧弹性盒)

    新弹性盒水平垂直居中参考:http://www.cnblogs.com/ooo0/p/7562884.html 新旧弹性盒样式参考:http://www.cnblogs.com/ooo0/p/7562 ...

  8. oh-my-zsh: bracketed-paste-magic:zle:47: not enough arguments for -U

    今天突然发现粘贴的时候就提示这个错误,通过查阅资料已经解决 解决方法 分析问题,是oh-my-zsh的bracketed-paste-magic功能出现了异常,并未找到更好的方法,暂时先禁用掉. 修改 ...

  9. hdu5306 Explosion

    题目链接 题意 有n个房间,每个房间里面有若干把钥匙,每把钥匙可以打开对应的一扇门.如果手中没有钥匙,就要随机轰炸一个房间来打开这个房间.如果有钥匙,就要去打开这些房间.问期望轰炸次数是多少. 思路 ...

  10. ON DUPLICATE KEY UPDATE单个增加更新及批量增加更新的sql

    转: ON DUPLICATE KEY UPDATE单个增加更新及批量增加更新的sql 本文为博主原创,转载请注明出处. 在实际应用中,经常碰到导入数据的功能,当导入的数据不存在时则进行添加,有修改时 ...