C#从MySQL操作数据库

        添加引用MySql.Data.dll

        users表如图

        

        image表如图

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

namespace CSharp直接连接MySQL
{
    class Program
    {
        static void Main(string[] args)
        {
            //Read();
            //Insert();
            //Update();
            //Delete();
            // ReadUsersCount();
            //ExcuteScalar();

            /*
            Console.WriteLine( VerifyUser("wangjun", "45"));
            Console.WriteLine(VerifyUser("ee", "ewert"));
            Console.ReadKey();*/


            //SaveImageToDB();

            LoadImageFromDB();
        }

        /// <summary>
        /// 读取数据库中数据
        /// </summary>
        static void Read()
        {
            string connectStr = "server=127.0.0.1;port=3306;database=mygamedb;user=root;password=root;";
            MySqlConnection conn = new MySqlConnection(connectStr);//仍还没有建立连接

            try
            {
                conn.Open();//建立连接

                string sql = "select * from users";//sql语句

                MySqlCommand cmd = new MySqlCommand(sql, conn);//建立命令

                /*********SQL操作**************************************************
                /**    cmd.ExecuteReader();//执行一些查询                       ***
                /**    cmd.ExecuteNonQuery();//插入 修改 删除                   ***
                /**    cmd.ExecuteScalar();//执行一些查询,返回一个单个的值     ***
                ******************************************************************/

                MySqlDataReader reader = cmd.ExecuteReader();//执行一些查询

                /*单行读取*************************
                reader.Read();//调用一次读得数据一行数据,如果读取成功返回true(此处为第一行)
                //reader[0]表示第一行的第一列数据
                Console.WriteLine(reader[0].ToString() + "," + reader[1].ToString() + "," + reader[2].ToString());

                reader.Read();//调用一次读得数据一行数据(此处为第2行)
                //reader[0]表示第2行的第一列数据
                Console.WriteLine(reader[0].ToString() + "," + reader[1].ToString() + "," + reader[2].ToString());
                **************************************/

                while (reader.Read())//整个表读取完
                {
                    //Console.WriteLine(reader[0].ToString() + "," + reader[1].ToString() + "," + reader[2].ToString());//第一种通过reader[i]得到列
                    //Console.WriteLine(reader.GetInt32(0) + "," + reader.GetString(1) + "," + reader.GetString(2));//第二种,通过列的索引(从0开始),并按所在列的值类型得到
                    Console.WriteLine(reader.GetInt32("id") + "," + reader.GetString("username") + "," + reader.GetString("password"));//第3种,通过列的名字,并按所在列的值类型得到

                }
                Console.WriteLine("已经建立连接");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                conn.Close();
            }
            Console.ReadKey();
         }

        /// <summary>
        /// 插入数据
        /// </summary>
        static void Insert()
        {
            string connectStr = "server=127.0.0.1;port=3306;database=mygamedb;user=root;password=root;";
            MySqlConnection conn = new MySqlConnection(connectStr);//仍还没有建立连接

            try
            {
                conn.Open();//建立连接
                Console.WriteLine("已经建立连接");

                //string sql = "insert into users(username,password) values('6-14u','88888')";//sql语句
                string sql = "insert into users(username,password,registerdate) values('e14u','11111','"+DateTime.Now+"')";//sql语句

                MySqlCommand cmd = new MySqlCommand(sql, conn);//建立命令

               int result= cmd.ExecuteNonQuery();//返回int值,影响了几行

                Console.WriteLine("插入成功,影响" + result + "行");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                conn.Close();
            }
            Console.ReadKey();
        }

        /// <summary>
        /// 修改数据
        /// </summary>
        static void Update()
        {
            string connectStr = "server=127.0.0.1;port=3306;database=mygamedb;user=root;password=root;";
            MySqlConnection conn = new MySqlConnection(connectStr);//仍还没有建立连接

            try
            {
                conn.Open();//建立连接
                Console.WriteLine("已经建立连接");

                //string sql = "insert into users(username,password) values('6-14u','88888')";//sql语句
                string sql = "update users set username='WANGJUN',password='WANGJUN' where id=2";//sql语句

                MySqlCommand cmd = new MySqlCommand(sql, conn);//建立命令

                int result = cmd.ExecuteNonQuery();//返回int值,影响了几行

                Console.WriteLine("修改成功,影响" + result + "行");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                conn.Close();
            }
            Console.ReadKey();
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        static void Delete()
        {
            string connectStr = "server=127.0.0.1;port=3306;database=mygamedb;user=root;password=root;";
            MySqlConnection conn = new MySqlConnection(connectStr);//仍还没有建立连接

            try
            {
                conn.Open();//建立连接
                Console.WriteLine("已经建立连接");

                //string sql = "insert into users(username,password) values('6-14u','88888')";//sql语句
                string sql = "delete from users where id=7";//sql语句

                MySqlCommand cmd = new MySqlCommand(sql, conn);//建立命令

                int result = cmd.ExecuteNonQuery();//返回int值,影响了几行

                Console.WriteLine("删除成功,影响" + result + "行");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                conn.Close();
            }
            Console.ReadKey();
        }

        /// <summary>
        /// 获取行数
        /// </summary>
        static void ReadUsersCount()
        {
            string connectStr = "server=127.0.0.1;port=3306;database=mygamedb;user=root;password=root;";
            MySqlConnection conn = new MySqlConnection(connectStr);//仍还没有建立连接

            try
            {
                conn.Open();//建立连接
                Console.WriteLine("已经建立连接");

                string sql = "select count(*) from users";//sql语句

                MySqlCommand cmd = new MySqlCommand(sql, conn);//建立命令

                MySqlDataReader reader = cmd.ExecuteReader();//执行一些查询

                reader.Read();

                int count = Convert.ToInt32(reader[0].ToString());
                Console.WriteLine(count);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                conn.Close();
            }
            Console.ReadKey();
        }

        /// <summary>
        /// 获取行数
        /// </summary>
        static void ExcuteScalar()
        {
            string connectStr = "server=127.0.0.1;port=3306;database=mygamedb;user=root;password=root;";
            MySqlConnection conn = new MySqlConnection(connectStr);//仍还没有建立连接

            try
            {
                conn.Open();//建立连接
                Console.WriteLine("已经建立连接");

                string sql = "select count(*) from users";//sql语句

                MySqlCommand cmd = new MySqlCommand(sql, conn);//建立命令

                object o = cmd.ExecuteScalar();
                
                Console.WriteLine(Convert.ToUInt32( o.ToString()));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                conn.Close();
            }
            Console.ReadKey();
        }

        /// <summary>
        /// 传递参数,验证账号和密码在数据库中是否存在
        /// </summary>
        /// <param name="username">账户</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        static bool VerifyUser(string username,string password)
        {
            string connectStr = "server=127.0.0.1;port=3306;database=mygamedb;user=root;password=root;";
            MySqlConnection conn = new MySqlConnection(connectStr);//仍还没有建立连接

            try
            {
                conn.Open();//建立连接
                Console.WriteLine("已经建立连接");

                //**********第一种,将参数传递到SQL语句中,按查询条件组拼**************************
                //string sql = "select * from users where username='"+username+"' and password='"+password+"'";//sql语句

                //***********第二种,在SQL语句中定义参数,然后用命令设置参数(用AddWithValue)************************
                string sql = "select * from users where username=@para1 and password=@para2";//sql语句

                MySqlCommand cmd = new MySqlCommand(sql, conn);//建立命令
                cmd.Parameters.AddWithValue("para1", username);
                cmd.Parameters.AddWithValue("para2", password);

                MySqlDataReader reader =cmd.ExecuteReader();

                while (reader.Read())
                {
                    return true;
                }
            }

            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                conn.Close();
            }
            return false;
        }

        /// <summary>
        /// 向数据库中上传(插入)图片,图片放于工程目录下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void SaveImageToDB()
        {
            byte[] imagebytes = null;
            string path = "imageTest.jpg";

            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            imagebytes = br.ReadBytes((int)fs.Length);

            string connectStr = "server=127.0.0.1;port=3306;database=mygamedb;user=root;password=root;";
            MySqlConnection conn = new MySqlConnection(connectStr);//仍还没有建立连接

            try
            {
                conn.Open();//建立连接
                Console.WriteLine("已经建立连接");

                string sql = "insert into image(imagefile,imagedata) values(@para1,@para2)";//sql语句

                MySqlCommand cmd = new MySqlCommand(sql, conn);//建立命令
                cmd.Parameters.AddWithValue("para1", "image1");
                cmd.Parameters.AddWithValue("para2", imagebytes);
                

                int result = cmd.ExecuteNonQuery();//返回int值,影响了几行

                Console.WriteLine("插入图片成功,影响" + result + "行");
            }

            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                conn.Close();
            }
            Console.ReadKey();
        }

        static void LoadImageFromDB()
        {
            byte[] imagebytes = null;
            
            string connectStr = "server=127.0.0.1;port=3306;database=mygamedb;user=root;password=root;";
            MySqlConnection conn = new MySqlConnection(connectStr);//仍还没有建立连接

            try
            {
                conn.Open();//建立连接
                Console.WriteLine("已经建立连接");

                string sql = "select imagefile,imagedata from image where imagefile='image1'";//sql语句

                MySqlCommand cmd = new MySqlCommand(sql, conn);//建立命令
                
                MySqlDataReader reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    
                    imagebytes = (byte[])reader[1];
                }
                MemoryStream ms = new MemoryStream(imagebytes);
                System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
                image.Save("D:\\");
                Console.WriteLine("读取图片成功");
            }

            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                conn.Close();
            }
            Console.ReadKey();
        }
    }
}


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页