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

2018-09-05 07:47:54来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

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

第一部分:数据库创建

数据库采用mysql 5.7.18, 数据库名称为MyUser, 内部有一张表 user.字段有 Id,UserName,Psd,Tel

 

第二部分:数据库连接与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请求

 前端页面设计为:

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:启动服务端程序

 

 

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

3 添加结果

 

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

 

 

 

 

 

 

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:前端给div加滚动条样式修改

下一篇:为何要清除浮动?如何清除?