Can JavaScript connect with MySQL?

前端 未结 19 2015
小鲜肉
小鲜肉 2020-11-22 16:18

Can JavaScript connect with MySQL? If so, how?

19条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 16:41

    Yes you can. MySQL connectors use TCP for connection, and in JS there is an little modified version of TCP client called Websocket. But you can't directly connect to MySQL server with websocket. You will need some 3rd party bridge between websocket and mysql. It receive query from websocket, send it to mysql, response result and resend to JS.

    And this is my example bridge written in C# with websocket-sharp library:

    class JSQLBridge : WebSocketBehavior
    {
        MySqlConnection conn;
    
        protected override void OnMessage(MessageEventArgs e)
        {
            if (conn == null)
            {
                try
                {
                    conn = new MySqlConnection(e.Data);
                    conn.Open();
                }
                catch (Exception exc)
                {
                    Send(exc.Message);
                }
            }
            else
            {
                try
                {
                    MySqlCommand cmd = new MySqlCommand(e.Data, conn);
                    cmd.ExecuteNonQuery();
                    Send("success");
                }
                catch (Exception exc)
                {
                    Send(exc.Message);
                }
            }
        }
    
        protected override void OnClose(CloseEventArgs e)
        {
            if (conn != null)
                conn.Close();
        }
    }
    

    JS side:

    var ws = new WebSocket("ws://localhost/");
    
    ws.send("server=localhost;user=root;database=mydb;");
    
    ws.send("select * from users");
    

提交回复
热议问题