小结一下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. open-falcon详解

    先扔出一张官方的架构图, agent是用于采集机器的监控指标,然后每60秒就会push给transfer,agent与transfer是建立了长连接的,传输速度会比较快: transfer接受到数据后 ...

  2. ViewHolder模式的简洁写法

    大家通常怎么写ViewHolder呢? ViewHolder holder = null; if(convertView == null){ convertView = mInflater.infla ...

  3. Android assets res 文件夹的区别

    大家都知道建立一个Android项目后会产生assets与res的两个文件夹,理论上他们都是存放资源的文件夹,那么他们到底有什么区别呢? 1.assets:不会在R.java文件下生成相应的标记,存放 ...

  4. js多回调函数

    多回调问题 前端编程时,大多通过接口交换数据,接口调用都是异步的,处理数据都是在回调函数里. 假如需要为一个用户建立档案,需要准备以下数据,然后调用建档接口 name     // 用户名字 使用接口 ...

  5. 配置日志中显示IP

    package com.demo.conf; import ch.qos.logback.classic.pattern.ClassicConverter; import ch.qos.logback ...

  6. 让Mac 可以使用mysql -u用户直接连接数据库

    在执行完安装版本的mysql数据库后,会发现执行mysql还是会出现 command not found的错误:解决方案 方案1.设置软连接到/usr/local/bin下在命令行下输入如下 ln - ...

  7. jsp (1)

    一.jsp介绍: jsp是servlet的一种包装.是html+js+css+servlet. jsp文件无需配置,如果修改了jsp文件不需要reload应用. jsp访问方法:直接访问文件名.jsp ...

  8. js 获取当前时间 年月日

    var datetime = new Date(); var year = datetime.getFullYear(); var month = datetime.getMonth() + 1 &l ...

  9. A1046. Shortest Distance

    The task is really simple: given N exits on a highway which forms a simple cycle, you are supposed t ...

  10. Django(十九)Ajax全套

    参考博客:http://www.cnblogs.com/wupeiqi/articles/5703697.html 提交: - Form - Ajax 一.Ajax,偷偷向后台发请求 - XMLHtt ...