Can JavaScript connect with MySQL?

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

Can JavaScript connect with MySQL? If so, how?

相关标签:
19条回答
  • 2020-11-22 16:43

    You can connect to MySQL from Javascript through a JAVA applet. The JAVA applet would embed the JDBC driver for MySQL that will allow you to connect to MySQL.

    Remember that if you want to connect to a remote MySQL server (other than the one you downloaded the applet from) you will need to ask users to grant extended permissions to applet. By default, applet can only connect to the server they are downloaded from.

    0 讨论(0)
  • 2020-11-22 16:43

    Of course you can. In Nodejs you can connect server side JavaScript with MySQL using MySQL driver. Nodejs-MySQL

    0 讨论(0)
  • 2020-11-22 16:47

    You can send AJAX requests to some server-side RESTful wrappers for MySQL, such as DBSlayer, PhpRestSQL or AlsoSQL (for Drizzle, a fork of MySQL).

    0 讨论(0)
  • 2020-11-22 16:48

    If you're not locked on MySQL you can switch to PostgreSQL. It supports JavaScript procedures (PL/V8) inside the database. It is very fast and powerful. Checkout this post.

    0 讨论(0)
  • 2020-11-22 16:50

    Depending on your environment, you could use Rhino to do this, see Rhino website. This gives you access to all of the Java libraries from within JavaScript.

    0 讨论(0)
  • 2020-11-22 16:50

    JavaScript can't connect directly to DB to get needed data but you can use AJAX. To make easy AJAX request to server you can use jQuery JS framework http://jquery.com. Here is a small example

    JS:

    jQuery.ajax({
    type: "GET",
    dataType: "json",
    url: '/ajax/usergroups/filters.php',
    data: "controller=" + controller + "&view=" + view,
    success: function(json)
    {
        alert(json.first);
        alert(json.second);
    });
    

    PHP:

    $out = array(); 
    
    // mysql connection and select query
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    
    try {
      die("Connection failed: " . $conn->connect_error);
    
      $sql = "SELECT * FROM [table_name] WHERE condition = [conditions]";
      $result = $conn->query($sql);
    
    if ($result->num_rows > 0) {
      // output data of each row
      while($row = $result->fetch_assoc()) {
        $out[] = [
           'field1' => $row["field1"],
           'field2' => $row["field2"]
        ];
      }
    } else {
      echo "0 results";
    }
    
    } catch(Exception $e) {
      echo "Error: " . $e->getMessage();
    }
        echo json_encode($out);
    
    0 讨论(0)
提交回复
热议问题