当前位置:   article > 正文

c#操作mysql数据库_c# 操作mysql

c# 操作mysql

1、下载mysql.Data.dll,在解决方案->引用中引入,并在文件头部引入

using MySql.Data.MySqlClient;

2、创建MySqlConnection对象(链接库)

string connstr = "data source=localhost;database=cs_test;user id=root;password=123456;pooling=false;charset=utf8";//pooling代表是否使用连接池
MySqlConnection conn = new MySqlConnection(connstr);

 3、创建对应操作的MySqlCommand对象(测试数据库表名characters,属性列:id,names,passwords)

string sql = "select * from characters";
MySqlCommand cmd = new MySqlCommand(sql,conn);

4、针对不同操作,MySqlCommand对象有三个常用方法

(1)查找多行 : ExecuteReader()方法

返回一个MysqlDataReader对象,包含多个行,可以用其Read方法逐行读取。

对于每行元素,可以用getXXX()方法读取属性值,XXX为该属性类型,参数为属性名或者该属性为这张表的第几列。

可以用IsDBNull()方法判断是否为空,参数只能是该属性为这张表的第几列(即只能是数字)

复制代码

    conn.Open();
    MySqlDataReader reader = cmd.ExecuteReader();
    Console.WriteLine("id\t姓名\t密码");
    while (reader.Read())
    {
        Console.Write(reader.GetInt32("id")+"\t");
        if (reader.IsDBNull(1))
        {
            Console.Write("空\t");
        }
        else
        {
            Console.Write(reader.GetString("names")+"\t");
        }
        if (reader.IsDBNull(2))
        {
            Console.Write("空\n");
        }
        else
        {
        Console.Write(reader.GetString("passwords")+"\n");
        }
    }
    conn.Close();

复制代码

 

(2)查找单个: ExecuteScalar()

返回值为查找到的元祖第一个属性,以object类型返回

string sql2 = "select names from characters where id=2";
MySqlCommand cmd2 = new MySqlCommand(sql2,conn);
conn.Open();
string names = cmd2.ExecuteScalar().ToString();
Console.WriteLine(names);
conn.Close();

(3)增、删、改: ExecuteNonQuery()

返回值为int,不成功是0,成功是1

复制代码

string sql3 = "insert into characters (names,passwords) values ('XXX','1234456')";
MySqlCommand cmd3 = new MySqlCommand(sql3,conn);
conn.Open();
int s = cmd3.ExecuteNonQuery();
if (s == 0) 
Console.WriteLine("false");
else 
Console.WriteLine("success");
conn.Close();

复制代码

5、完整代码

复制代码

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

namespace mysql_test
{
    class mysqlcz{
        public mysqlcz()
        {
            string connstr = "data source=localhost;database=csceshi;user id=root;password=123456;pooling=false;charset=utf8";
            using (MySqlConnection conn = new MySqlConnection(connstr))
            {
                string sql = "select * from characters";
                MySqlCommand cmd = new MySqlCommand(sql,conn);
                conn.Open();
                MySqlDataReader reader = cmd.ExecuteReader();
                Console.WriteLine("id\t姓名\t密码");
                while (reader.Read())
                {
                    Console.Write(reader.GetInt32("id")+"\t");
                    if (reader.IsDBNull(1))
                    {
                        Console.Write("空\t");
                    }
                    else
                    {
                        Console.Write(reader.GetString("names")+"\t");
                    }

                    if (reader.IsDBNull(2))
                    {
                        Console.Write("空\n");
                    }
                    else
                    {
                        Console.Write(reader.GetString("passwords")+"\n");
                    }
                }
                conn.Close();
                string sql2 = "select names from characters where id=2";
                MySqlCommand cmd2 = new MySqlCommand(sql2,conn);
                conn.Open();
                string names = cmd2.ExecuteScalar().ToString();
                Console.WriteLine(names);
                conn.Close();

                string sql3 = "insert into characters (names,passwords) values ('XXX','1234456')";
                MySqlCommand cmd3 = new MySqlCommand(sql3,conn);
                conn.Open();
                int s = cmd3.ExecuteNonQuery();
                if (s == 0) Console.WriteLine("false");
                else Console.WriteLine("success");
                conn.Close();
            }
            Console.ReadLine();
        }        
        
       
    }
    class Program
    {
        static void Main(string[] args)
        {
            mysqlcz mt = new mysqlcz();
        }
    }
}

复制代码

 6、sql语句参数化

为防止sql注入,尽量不要使用字符串拼接的方法拼接sql字符串

复制代码

string uname=Console.ReadLine();
string upwd=Console.ReadLine();//获取用户输入
string sql="insert into characters (names,passwords) values (@name,@pwd)";//使用@符构造sql变量
MysqlCommand cmd = new MysqlCommand(sql,conn);
//使用MysqlCommand对象的parameters属性,该属性为像sql语句传递的参数集合,使用add方法向其中添加参数,参数以MysqlParameters对象形式传递
cmd.parameters.Add(new MysqlParametes("@name",uname));
cmd.parameters.Add(new MysqlParameters("@pwd",upwd));
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();

复制代码

C# 利用mysql.data 在mysql中创建数据库及数据表

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using MySql.Data.MySqlClient;

 

namespace CA_Mysql

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("1.创建数据表吗?");

            Console.ReadKey();

            NewDatatable("localhost""root""pwd""newtest1""newtb2");

            Console.ReadLine();

        }

 

        /// <summary>

        /// 创建新的数据库

        /// </summary>

        static void NewDatabase(string dbSource ,string dbUid,string dbPwd,string dbName)

        {

            //创建连接字符串con

            MySqlConnection con = new MySqlConnection("Data Source=" + dbSource + ";Persist Security Info=yes;UserId=" + dbUid + "; PWD="+dbPwd+";");

            //创建数据库的执行语句

            MySqlCommand cmd = new MySqlCommand("CREATE DATABASE " + dbName, con);

            con.Open();

            //执行语句

            int res = cmd.ExecuteNonQuery();

            con.Close();

        }

 

        /// <summary>

        /// 创建数据表

        /// </summary>

        static void NewDatatable(string dbSource, string dbUid, string dbPwd, string dbName,string tbName)

        {

            //创建连接字符串con

            MySqlConnection con = new MySqlConnection("Data Source=" + dbSource + ";Persist Security Info=yes;UserId=" + dbUid + "; PWD=" + dbPwd + ";");

            string newTableCMD = "USE " + dbName + "; CREATE TABLE `TESTTABLE3` (`Id_` int(11) NOT NULL AUTO_INCREMENT,`NAME` VARCHAR(32) NOT NULL,PRIMARY KEY(`Id_`));";

            MySqlCommand cmd = new MySqlCommand(newTableCMD,con);

            con.Open();

            //MySqlCommand cmdUseDB = new MySqlCommand("USE " + dbName, con);

            //cmdUseDB.ExecuteNonQuery();

            int res = cmd.ExecuteNonQuery();

            con.Close();

        }

 

    }

}

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/486866
推荐阅读
相关标签
  

闽ICP备14008679号