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扩展 ...
随机推荐
- linux添加lvm磁盘大小,命令行创建swap
添加硬盘 添加一块硬盘. 重新扫描硬盘 echo "- - -" > /sys/class/scsi_host/host0/scan echo "- - -&quo ...
- 【转】从此以后谁也别说我不懂LDO了!
LDO是个很简单的器件,但是我跟客户沟通的过程中,发现客户工程师的技术水平参差不齐,有的工程师只是follow 别人以前的设计,任何原理和设计方法都不懂,希望大家看完这篇文章都能成为LDO 专家. 第 ...
- 136.137.260. Single Number && 位运算
136. Single Number 意思就是给你一堆数,每个数都出现了两次,只有一个数只出现了一次,找出这个数 位运算(和c艹一样) &:按位与 |:按位或 ^:异或(一样为0,不一样为1) ...
- 工作队列.py
#对列模式图Work Queue背后的主要思想是避免立即执行资源密集型任务的时,需要等待其他任务完成.所以我们把任务安排的晚一些,我们封装一个任务到消息中并把它发送到队列,一个进程运行在后端发送并最终 ...
- A.01.01—模块的输入—低端输入
汽车电子模块的输入一般包含数字量低端输入.数字量高端输入.模拟量输入.脉宽调制输入.总线信号输入.脉冲信号输入,对于无线信号输入和视频信号音频信号我们不做讨论. 数字量低端输入是应用最为广泛的一种输入 ...
- 20165223《Java程序设计》第七周Java学习总结
教材学习内容总结 第11章-JDBC与MySQL数据库 要点 MySQL数据库管理系统 连接MySQL数据库 查询操作(基础) 更新.添加.删除(基础) 预处理语句(重点) 通用查询(难点) 事务 笔 ...
- Ubuntu16.04下的NetCore环境搭建(附录含Ubuntu 18.04 安装 NetCore2.1)
跨平台系列汇总:http://www.cnblogs.com/dunitian/p/4822808.html#linux VSCode安装:http://www.cnblogs.com/dunitia ...
- spring中的@Bean是否一定要与@Configuration一起用
版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/little_newBee/article/details/80383691 在使用sprin ...
- LINQ的基础使用方法
//新建一个项目 //项目下新建一个App_Code文件夹 //在文件夹内添加一个LINQ TO SQL,这个操作就相当于创建了一个实体类 //连接数据库后把表拖入到服务器资源管理器中 //创建数据访 ...
- (转)java中引用传递和值传递
https://blog.csdn.net/javazejian/article/details/51192130 https://www.cnblogs.com/perfy/archive/2012 ...