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扩展 ...
随机推荐
- EasyFlash 的初始化配置
@2019-02-18 [小记] EasyFlash的初始化流程 easyflash_init ---> ef_port_init ---> sfud_init ---> sfud_ ...
- Chemical table CFR500 div2D(并查集)
给定的一个n*m的区域内,给出一些点的坐标,这些点上有一个元素,如果在矩形的子矩形的三个点都有元素,那么第四个点的元素可以自己产生,其他的元素需要购买,问最少需要购买多少中元素才可以把这个区域给填满. ...
- hasattr
语法: hasattr(object,name) 检测类对象是否具有该name属性或方法
- CentOS下Denyhosts的安装和使用
安装 默认yum就可以进行安装 yum install denyhosts* -y 配置 配置文件路径: /etc/denyhosts.conf ; YUM安装时其实已经配置好了大部分,我们自己稍作改 ...
- POJ--3614 Sunscreen(贪心)
题目 3614 Sunscreen 2500*2500直接排序暴力贪心 #include<iostream> #include<cstring> #include<alg ...
- poj1193 内存分配
气死我了...这个毒瘤内存分配..... 优先队列 + 链表模拟,看起来搞一搞就好了却WA来WA去... 最后对拍手动找才发现错误: erase的时候不要急急忙忙插入wait!要把同一时期的erase ...
- Django 跨域请求
跨域:通过js或python在不同的域之间进行数据传输或通信,比如用ajax向一个不同的域请求数据,或者通过js获取页面中不同域的框架中(Django)的数据.只要协议.域名.端口有任何一个不同,都被 ...
- 【洛谷P2925 [USACO08DEC]干草出售Hay For Sale】
题意翻译 题目描述 农民john面临一个很可怕的事实,因为防范失措他存储的所有稻草给澳大利亚蟑螂吃光了,他将面临没有稻草喂养奶牛的局面.在奶牛断粮之前,john拉着他的马车到农民Don的农场中买一些稻 ...
- listview 样式 LVS_REPORT 与 LVS_EDITLABELS 编辑单元格时,当前行第一列内容不显示
今天想做一个可编辑单元格的 listview,样式是 LVS_REPORT 与 LVS_EDITLABELS 网上搜索了一些相关资料,照葫芦画瓢写了一个,可测试的时候发现,当从第2列开始编辑的时候,第 ...
- 终于解决了用JAVA写窗口程序在不同的windows界面下的显示保持一致。
好像是两三年前的时候发现这个问题. 由于在windows经典界面与windows xp界面下,窗口的标题栏的高度是不一样的. 所以我们在用Java写GUI程序的时候,会遇到一个问题. 当我把一个JFr ...