C#--连接Mysql数据库

首先要在项目中添加NuGet包
在当前项目的项目菜单中选择管理NuGet程序包
在这里插入图片描述
在浏览界面中搜索Mysql.data并安装第一个
在这里插入图片描述
在之后的每一次需要使用连接MySql数据库时就在开头加一个
using Mysql.Data.MysqlClient;
在这里插入图片描述
这便完成了C#连接MySql的环境配置
接下来是使用的过程:
1.创建一个String字段,储存连接数据库的相关信息
server=localhost;port=3306;user=连接数据库用户名;password=密码database=数据库名字
2.创建MySqlConnection 对象
3.用该对象调用open()函数,连接数据库
4.调用close()来关闭数据库连接

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace MySqlCmd
{
    class Program
    {
        static void Main(string[] args)
        {
            string connetStr = "server=localhost;port=3306;user=root;password=123456;database=classicmodels;";
            MySqlConnection conn = new MySqlConnection(connetStr);
            try
            {
                conn.Open();
                Console.WriteLine("-建立连接");

            }
            catch(MySqlException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                conn.Close();
            }
            
        }
    }
}

注意:在连接数据库时最好使用 try catch 语句,来保证连接可靠性

运行结果:
在这里插入图片描述
ExecuteReader——用于查询数据库。查询结果是返回MySqlDataReader对象,MySqlDataReader包含sql语句执行的结果,并提供一个方法从结果中阅读一行。

ExecuteNonQuery——用于插入、更新和删除数据。

ExecuteScalar——用于查询数据时,返回查询结果集中第一行第一列的值,即只返回一个值。

一、对数据库的内容进行读取
1.建立一个string对象来存放MySql语句,如:select * from customer
2.用SQL语句为形参来创建一个MySqlCommand对象
3.使用ExcuteReader()函数来执行该SQl语句,并返回一个MySqlDataReader对象
4.通过调用MySqlDataReader对象的Read()来返回一个布尔值,用于判断数据库中是否还有数据可读取
5.通过循环MySqlDataReader对象的GetInt32(int i),GetString(int i)等等获得相应类型数据的函数来得到数据
注意:int i 参数为对应表格中列数,从0开始

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace MySqlCmd
{
    class Program
    {
        static void Main(string[] args)
        {
            string connetStr = "server=localhost;port=3306;user=root;password=123456;database=classicmodels;";
            MySqlConnection conn = new MySqlConnection(connetStr);
            try
            {
                conn.Open();
                string sqlCmd = "select * from customers";
                MySqlCommand cmd = new MySqlCommand(sqlCmd, conn);
                MySqlDataReader reader = cmd.ExecuteReader();
                Console.WriteLine("customerNumber\tcustomerName\n");
                while (reader.Read())
                {
                    Console.WriteLine("{0}\t{1}", reader.GetInt32(0), reader.GetString(1));
                }
            }
            catch(MySqlException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                conn.Close();
            }
            
        }
    }
}

为了使输出的结果易于阅读,可使用’\t’制表符号。
运行结果
在这里插入图片描述

二、对数据库进行增删改操作
使用ExecuteNonQuery()函数,返回值为数据表中被影响的行数。只有Update、Insert、Delete会影响行数,当返回值为-1时,说明操作执行失败,当返回值为0时说明无影响。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace MySqlCmd
{
    class Program
    {
        static void Main(string[] args)
        {
            string connetStr = "server=localhost;port=3306;user=root;password=123456;database=Demo3;";
            MySqlConnection conn = new MySqlConnection(connetStr);
            try
            {
                conn.Open();
                string sqlCmd = "delete from customer where userId=4";
                MySqlCommand cmd = new MySqlCommand(sqlCmd, conn);
                int num = cmd.ExecuteNonQuery();
                Console.WriteLine("影响行数" + num);
            }
            catch(MySqlException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                conn.Close();
            }
            
        }
    }
}



运行结果:
在这里插入图片描述
三、ExcuteScalar()
执行CommandText属性指定的内容,并返回执行结果集的第一行第一列的值(此方法只用来执行Select语句),例如,在使用select count (*) from …语句返回就行数时,并不需要遍历所有行,就可以用ExcuteScalar()函数。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace MySqlCmd
{
    class Program
    {
        static void Main(string[] args)
        {
            string connetStr = "server=localhost;port=3306;user=root;password=123456;database=classicmodels;";
            MySqlConnection conn = new MySqlConnection(connetStr);
            try
            {
                conn.Open();
                string sqlCmd = "select * from customers";
                MySqlCommand cmd = new MySqlCommand(sqlCmd, conn);
                Console.WriteLine(cmd.ExecuteScalar());
            }
            catch(MySqlException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                conn.Close();
            }
            
        }
    }
}



运行结果:
在这里插入图片描述
四、读取数据DataReader的属性与方法
属性:
1.FieldCount—说去字段的数目
2.HasRows—数据读取器是否包含一行或多行,false表示没有行
方法:
GetName(col)获取第col列的字段名
GetOrdinal()获取字段名为Name的列的序号
Read()读取下一条记录,返回布尔值 True表示还有也下一条数据
Close()关闭数据对象

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值