欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MySql+Socket 完成数据库的增查Demo

程序员文章站 2022-10-05 07:54:43
需求: 利用MySql数据库结合前端技术完成用户的注册(要求不使用Web服务技术),所以 Demo采用Socket技术实现Web通信. 第一部分:数据库创建 数据库采用mysql 5.7.18, 数据库名称为MyUser, 内部有一张表 user.字段有 Id,UserName,Psd,Tel 第二 ......

         需求: 利用mysql数据库结合前端技术完成用户的注册(要求不使用web服务技术),所以 demo采用socket技术实现web通信.

第一部分:数据库创建

数据库采用mysql 5.7.18, 数据库名称为myuser, 内部有一张表 user.字段有 id,username,psd,tel

 

MySql+Socket 完成数据库的增查Demo

第二部分:数据库连接与socket通信

创建控制台程序(服务端程序),添加以下类

1 mysqlhelper

 建立mysqlhelper 类,用于实现数据库操作

public class mysqlhelper
    {
        //数据库连接字符串 
        public static string conn = "database='myuser';data source='localhost';user id='root';password='';charset='utf8'"; //xxx的为修改项
        
        public static   void setconn(string username = "root", string password="", string ip= "localhost",   string database="myuser")
        {
            conn = "datasource=" + ip + ";username=" + username + ";password=" + password + ";database=" + database + ";charset=utf8";
           
        }
        /// <summary> 
        /// 给定连接的数据库用假设参数执行一个sql命令(不返回数据集) 
        /// </summary> 
        /// <param name="connectionstring">一个有效的连接字符串</param> 
        /// <param name="cmdtype">命令类型(存储过程, 文本, 等等)</param> 
        /// <param name="cmdtext">存储过程名称或者sql命令语句</param> 
        /// <param name="commandparameters">执行命令所用参数的集合</param> 
        /// <returns>执行命令所影响的行数</returns> 
        public static int executenonquery(string connectionstring, commandtype cmdtype, string cmdtext, params mysqlparameter[] commandparameters)
        {

            mysqlcommand cmd = new mysqlcommand();

            using (mysqlconnection conn = new mysqlconnection(connectionstring))
            {
                preparecommand(cmd, conn, null, cmdtype, cmdtext, commandparameters);
                int val = cmd.executenonquery();
                cmd.parameters.clear();
                return val;
            }
        }

        /// <summary> 
        /// 用现有的数据库连接执行一个sql命令(不返回数据集) 
        /// </summary> 
        /// <param name="connection">一个现有的数据库连接</param> 
        /// <param name="cmdtype">命令类型(存储过程, 文本, 等等)</param> 
        /// <param name="cmdtext">存储过程名称或者sql命令语句</param> 
        /// <param name="commandparameters">执行命令所用参数的集合</param> 
        /// <returns>执行命令所影响的行数</returns> 
        public static int executenonquery(mysqlconnection connection, commandtype cmdtype, string cmdtext, params mysqlparameter[] commandparameters)
        {

            mysqlcommand cmd = new mysqlcommand();

            preparecommand(cmd, connection, null, cmdtype, cmdtext, commandparameters);
            int val = cmd.executenonquery();
            //cmd.parameters.clear();
            return val;
        }

        /// <summary> 
        ///使用现有的sql事务执行一个sql命令(不返回数据集) 
        /// </summary> 
        /// <remarks> 
        ///举例: 
        /// int result = executenonquery(connstring, commandtype.storedprocedure, "publishorders", new mysqlparameter("@prodid", 24)); 
        /// </remarks> 
        /// <param name="trans">一个现有的事务</param> 
        /// <param name="cmdtype">命令类型(存储过程, 文本, 等等)</param> 
        /// <param name="cmdtext">存储过程名称或者sql命令语句</param> 
        /// <param name="commandparameters">执行命令所用参数的集合</param> 
        /// <returns>执行命令所影响的行数</returns> 
        public static int executenonquery(mysqltransaction trans, commandtype cmdtype, string cmdtext, params mysqlparameter[] commandparameters)
        {
            mysqlcommand cmd = new mysqlcommand();
            preparecommand(cmd, trans.connection, trans, cmdtype, cmdtext, commandparameters);
            int val = cmd.executenonquery();
            cmd.parameters.clear();
            return val;
        }

        /// <summary> 
        /// 用执行的数据库连接执行一个返回数据集的sql命令 
        /// </summary> 
        /// <remarks> 
        /// 举例: 
        /// mysqldatareader r = executereader(connstring, commandtype.storedprocedure, "publishorders", new mysqlparameter("@prodid", 24)); 
        /// </remarks> 
        /// <param name="connectionstring">一个有效的连接字符串</param> 
        /// <param name="cmdtype">命令类型(存储过程, 文本, 等等)</param> 
        /// <param name="cmdtext">存储过程名称或者sql命令语句</param> 
        /// <param name="commandparameters">执行命令所用参数的集合</param> 
        /// <returns>包含结果的读取器</returns> 
        public static mysqldatareader executereader(string connectionstring, commandtype cmdtype, string cmdtext, params mysqlparameter[] commandparameters)
        {
            //创建一个mysqlcommand对象 
            mysqlcommand cmd = new mysqlcommand();
            //创建一个mysqlconnection对象 
            mysqlconnection conn = new mysqlconnection(connectionstring);

            //在这里我们用一个try/catch结构执行sql文本命令/存储过程,因为如果这个方法产生一个异常我们要关闭连接,因为没有读取器存在, 
            //因此commandbehaviour.closeconnection 就不会执行 
            try
            {
                //调用 preparecommand 方法,对 mysqlcommand 对象设置参数 
                preparecommand(cmd, conn, null, cmdtype, cmdtext, commandparameters);
                //调用 mysqlcommand 的 executereader 方法 
                mysqldatareader reader = cmd.executereader(commandbehavior.closeconnection);
                //清除参数 
                cmd.parameters.clear();
                return reader;
            }
            catch
            {
                //关闭连接,抛出异常 
                conn.close();
                throw;
            }
        }

        /// <summary> 
        /// 返回dataset 
        /// </summary> 
        /// <param name="connectionstring">一个有效的连接字符串</param> 
        /// <param name="cmdtype">命令类型(存储过程, 文本, 等等)</param> 
        /// <param name="cmdtext">存储过程名称或者sql命令语句</param> 
        /// <param name="commandparameters">执行命令所用参数的集合</param> 
        /// <returns></returns> 
        public static dataset getdataset(string connectionstring, commandtype cmdtype, string cmdtext, params mysqlparameter[] commandparameters)
        {
            //创建一个mysqlcommand对象 
            mysqlcommand cmd = new mysqlcommand();
            //创建一个mysqlconnection对象 
            mysqlconnection conn = new mysqlconnection(connectionstring);

            //在这里我们用一个try/catch结构执行sql文本命令/存储过程,因为如果这个方法产生一个异常我们要关闭连接,因为没有读取器存在,

            try
            {
                //调用 preparecommand 方法,对 mysqlcommand 对象设置参数 
                preparecommand(cmd, conn, null, cmdtype, cmdtext, commandparameters);
                //调用 mysqlcommand 的 executereader 方法 
                mysqldataadapter adapter = new mysqldataadapter();
                adapter.selectcommand = cmd;
                dataset ds = new dataset();

                adapter.fill(ds);
                //清除参数 
                cmd.parameters.clear();
                conn.close();
                return ds;
            }
            catch (exception e)
            {
                throw e;
            }
        }


        public static datatable getdatatable(string connectionstring, commandtype cmdtype, string cmdtext, params mysqlparameter[] commandparameters)
        {
            //创建一个mysqlcommand对象 
            mysqlcommand cmd = new mysqlcommand();
            //创建一个mysqlconnection对象 
            mysqlconnection conn = new mysqlconnection(connectionstring);

            //在这里我们用一个try/catch结构执行sql文本命令/存储过程,因为如果这个方法产生一个异常我们要关闭连接,因为没有读取器存在,

            try
            {
                //调用 preparecommand 方法,对 mysqlcommand 对象设置参数 
                preparecommand(cmd, conn, null, cmdtype, cmdtext, commandparameters);
                //调用 mysqlcommand 的 executereader 方法 
                mysqldataadapter adapter = new mysqldataadapter();
                adapter.selectcommand = cmd;
                datatable ds = new datatable();

                adapter.fill(ds);
                //清除参数 
                cmd.parameters.clear();
                conn.close();
                return ds;
            }
            catch (exception e)
            {
                throw e;
            }
        }


        /// <summary> 
        /// 用指定的数据库连接字符串执行一个命令并返回一个数据集的第一列 
        /// </summary> 
        /// <remarks> 
        ///例如: 
        /// object obj = executescalar(connstring, commandtype.storedprocedure, "publishorders", new mysqlparameter("@prodid", 24)); 
        /// </remarks> 
        ///<param name="connectionstring">一个有效的连接字符串</param> 
        /// <param name="cmdtype">命令类型(存储过程, 文本, 等等)</param> 
        /// <param name="cmdtext">存储过程名称或者sql命令语句</param> 
        /// <param name="commandparameters">执行命令所用参数的集合</param> 
        /// <returns>用 convert.to{type}把类型转换为想要的 </returns> 
        public static object executescalar(string connectionstring, commandtype cmdtype, string cmdtext, params mysqlparameter[] commandparameters)
        {
            mysqlcommand cmd = new mysqlcommand();

            using (mysqlconnection connection = new mysqlconnection(connectionstring))
            {
                preparecommand(cmd, connection, null, cmdtype, cmdtext, commandparameters);
                object val = cmd.executescalar();
                cmd.parameters.clear();
                return val;
            }
        }

        /// <summary> 
        /// 用指定的数据库连接执行一个命令并返回一个数据集的第一列 
        /// </summary> 
        /// <remarks> 
        /// 例如: 
        /// object obj = executescalar(connstring, commandtype.storedprocedure, "publishorders", new mysqlparameter("@prodid", 24)); 
        /// </remarks> 
        /// <param name="connection">一个存在的数据库连接</param> 
        /// <param name="cmdtype">命令类型(存储过程, 文本, 等等)</param> 
        /// <param name="cmdtext">存储过程名称或者sql命令语句</param> 
        /// <param name="commandparameters">执行命令所用参数的集合</param> 
        /// <returns>用 convert.to{type}把类型转换为想要的 </returns> 
        public static object executescalar(mysqlconnection connection, commandtype cmdtype, string cmdtext, params mysqlparameter[] commandparameters)
        {

            mysqlcommand cmd = new mysqlcommand();

            preparecommand(cmd, connection, null, cmdtype, cmdtext, commandparameters);
            object val = cmd.executescalar();
            cmd.parameters.clear();
            return val;
        }




        /// <summary> 
        /// 准备执行一个命令 
        /// </summary> 
        /// <param name="cmd">sql命令</param> 
        /// <param name="conn">oledb连接</param> 
        /// <param name="trans">oledb事务</param> 
        /// <param name="cmdtype">命令类型例如 存储过程或者文本</param> 
        /// <param name="cmdtext">命令文本,例如:select * from products</param> 
        /// <param name="cmdparms">执行命令的参数</param> 
        private static void preparecommand(mysqlcommand cmd, mysqlconnection conn, mysqltransaction trans, commandtype cmdtype, string cmdtext, mysqlparameter[] cmdparms)
        {

            if (conn.state != connectionstate.open)
                conn.open();

            cmd.connection = conn;
            cmd.commandtext = cmdtext;

            if (trans != null)
                cmd.transaction = trans;

            cmd.commandtype = cmdtype;

            if (cmdparms != null)

            {

                foreach (mysqlparameter parm in cmdparms)
                    cmd.parameters.add(parm);
            }
        }

    }

  

2,user类与userhelper类

建立用户类user与用户操作类userhelper

user

public class user
    {
        public int id { get; set; }
        public string username { get; set; }
        public string psd { get; set; }
        public string phonenum { get; set; }

     
    }

  

userhelper

public   class userhelper
    {


        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="cmdtext"></param>
        /// <returns></returns>
        public static  list<user> getusers()
        {
            var cmdtext = "select * from users";
            var data = mysqlhelper.getdataset(mysqlhelper.conn, system.data.commandtype.text, cmdtext, new mysql.data.mysqlclient.mysqlparameter());
            list<user> userlist = new list<user>();
            foreach (datarow row in data.tables[0].rows)
            {
                user user = new user();
                user.id = int.parse(row[0].tostring());
                user.username=(row[1].tostring());
                user.psd=(row[2].tostring());
                user.phonenum=(row[3].tostring());
                userlist.add(user);
            }
            return userlist;
        }
        /// <summary>
        /// 根据姓名查找用户
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>

        public static  user getuserbyname(string name)
        {
            var cmdtext = "select * from users where username=?name";
            var pars = new mysql.data.mysqlclient.mysqlparameter("?name", name);
            var data = mysqlhelper.getdataset(mysqlhelper.conn, system.data.commandtype.text, cmdtext, pars);
            user user = new user();
            if (data.tables.count == 0)
            {
                return null;
            }
            if (data.tables[0].rows.count != 1)
            {
                return null;
            }
            foreach (datarow row in data.tables[0].rows)
            {               
                user.id = int.parse(row[0].tostring());
                user.username = (row[1].tostring());
                user.psd = (row[2].tostring());
                user.phonenum = (row[3].tostring());
                ;
            }
            return user;
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static bool adduser(user user)
        {
            var sqlinsert = "insert into users(username,psd,tel) values" +
               "('" + user.username + "','" + user.psd + "','" + user.phonenum + "')";           
            var parms = new mysqlparameter();

            var data = mysqlhelper.executenonquery(mysqlhelper.conn, system.data.commandtype.text, sqlinsert, parms);
           
            return data>0;


        }

    }

  

3 socket

网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket.socket本质是编程接口(api),对tcp/ip的封装,tcp/ip也要提供可供程序员做网络开发所用的接口,这就是socket编程接口;

利用socket技术,可以捕捉http请求,获取数据.构建sockethelper类,获取前端页面请求.默认socket 端口为8086

public class sockethelper
    {


        static socket m_socket = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
        /// <summary>
        /// socket初始化 
        /// </summary>
        public static bool  init()
        {
            try
            {
                m_socket.bind(new ipendpoint(ipaddress.any, 8086));
                m_socket.listen(100);
                m_socket.beginaccept(new asynccallback(onaccept), m_socket);
                console.writeline("开启socket服务成功!!");
                console.read();
                return true;
            }
            catch (exception )
            {
                console.writeline("开启socket服务失败!!,请检查网络,端口8086是否被占用!!!");
                console.read();
                return false;
            }
          
        }
        public static void route(string path, dictionary<string, string> param, socket response)
        {
            if (param.count == 1)
            {
                try
                {
                    var username = param["username"];
                    var searuser = userhelper.getuserbyname(username);
                    if (searuser != null)
                    {
                        homepage(response, "该用户名已经被占用!!");
                        console.writeline("** - **");
                        console.writeline("用户名" + username + "被占用");
                        console.writeline("");
                        homepage(response, "no");
                    }
                    else
                    {
                        homepage(response, "ok");
                    }
                }
                catch (exception e)
                {

                    homepage(response, e.message);
                    console.writeline("** - **");
                    console.writeline("发生错误,错误原因为" + e.message);
                    console.writeline("");
                }
               

                return;

            }
            else if (param.count == 3) {
                try
                {
                    user user = new user();
                    user.username = param["username"];
                    user.psd = param["psd"];
                    user.phonenum = param["phonenum"];
                    var issuccess = userhelper.adduser(user);
                    if (issuccess)
                    {
                        homepage(response, "ok");
                        console.writeline("** - **");
                        console.writeline("用户名为" + user.username + "已添加到数据库!!");
                        console.writeline("");
                    }
                    else
                    {
                        homepage(response, "no");
                        console.writeline("** - **");
                        console.writeline("用户名为" + user.username + "添加到数据库失败!!");
                        console.writeline("");
                    }
                }
                catch (exception e)
                {

                    homepage(response, e.message);
                    console.writeline("** - **");
                    console.writeline("发生错误,错误原因为" + e.message);
                    console.writeline("");
                }
            }
            else
            {
                homepage(response, "参数错误!!");
                console.writeline("** - **");
                console.writeline("参数错误" );
                console.writeline("");


            }
           

            return;
            
        }

        public static void onaccept(iasyncresult ar)
        {
            try
            {
                socket socket = ar.asyncstate as socket;
                socket new_client = socket.endaccept(ar);
                socket.beginaccept(new asynccallback(onaccept), socket);
                byte[] recv_buffer = new byte[1024 * 640];
                int real_recv = new_client.receive(recv_buffer);

                string recv_request = encoding.utf8.getstring(recv_buffer, 0, real_recv);
                console.writeline(recv_request);

                resolve(recv_request, new_client);
            }
            catch
            {

            }
        }

        public static void resolve(string request, socket response)
        {
            string[] strs = request.split(new string[] { "\r\n" }, stringsplitoptions.none);
            if (strs.length > 0)
            {
                string[] items = strs[0].split(' ');
                dictionary<string, string> param = new dictionary<string, string>();

                if (strs.contains(""))
                {
                    string post_data = strs[strs.length - 1];
                    if (post_data != "")
                    {
                        string[] post_datas = post_data.split('&');
                        foreach (string s in post_datas)
                        {
                            param.add(s.split('=')[0], s.split('=')[1]);
                        }
                    }
                }
                route(items[1], param, response);
            }
        }

        public static void homepage(socket response,string result)
        {
            string statusline = "http/1.1 200 ok\r\n";
            byte[] statusline_to_bytes = encoding.utf8.getbytes(statusline);

            string content = result;
            byte[] content_to_bytes = encoding.utf8.getbytes(content);

            string header = string.format("access-control-allow-origin:*\r\ncontent-type:text/html;charset=utf-8\r\ncontent-length:{0}\r\n", content_to_bytes.length);
            byte[] header_to_bytes = encoding.utf8.getbytes(header);

            response.send(statusline_to_bytes);
            response.send(header_to_bytes);
            response.send(new byte[] { (byte)'\r', (byte)'\n' });
            response.send(content_to_bytes);
            response.close();
        }
    }

  

第三部分 前端页面与ajax请求

 前端页面设计为:

MySql+Socket 完成数据库的增查Demo

ajax请求代码:

$('.red_button').click(function () {
  if (user_boolean && password_boolean && varconfirm_boolean && mobile_boolean == true) {
    $.ajax({
      type: 'post',
      url: 'http://127.0.0.1:8086/',
      data: {
        'username':$('#username').val(),
        'psd': $('#psd').val(),
        'phonenum': $('#phonenum').val()
      },
      success: function (data) {
        if (data == "ok") {
          alert("注册成功!!")
        } else {
          alert("data");
        }
        
      }

    });
  } 
  else {
    alert("请完善信息");
  }
});

 

至此,程序完成.运行程序进行验证.

1:启动服务端程序

MySql+Socket 完成数据库的增查Demo

 

 

2:启动前端页面,进行数据填写

MySql+Socket 完成数据库的增查Demo

3 添加结果

MySql+Socket 完成数据库的增查Demo

 

    至此 ,demo功能完成。之前没有试过利用socket技术完成ajax请求,这次也算是一次尝试,偶尔看到这个程序,以防以后需要 做个笔记..