Are there JavaScript bindings for MySQL?

后端 未结 9 1940
礼貌的吻别
礼貌的吻别 2020-12-17 00:56

I want to access a MySQL database directly from JavaScript code in an HTML page in Firefox.

Does such a library exist?

To be very clear, CGI+Ajax wil

9条回答
  •  轮回少年
    2020-12-17 01:57

    Javascript can access MySQL...but generally only on the server. I've done it with Rhino, a java based javascript interpreter. Just included the MySQL driver, and its available. I imagine you could probably do this with an applet as well.

    using Rhino, it would be something like this:

    var DATABASE = {
    
        database: 'blog_development',
        host: 'localhost',
        username: 'dbuser',
        password: 'dbpass'
    
    };
    
    function ArticleModel(properties) {
      for (var p in properties) {
        this[p] = properties[p];
      }
    }
    
    ArticleModel.findAll = function() {
        var results = [];
    
        var jsConnectionObj = new Packages.MysqlConnection();
        c = jsConnectionObj.open(DATABASE.host,
                                 DATABASE.database,
                                 DATABASE.username,
                                 DATABASE.password);
    
        if (c) {
          var s = c.createStatement();
          s.executeQuery("SELECT * FROM articles;");
          var rs = s.getResultSet();
          while (rs.next()) {
              results.push(new ArticleModel({
                id: rs.getInt("id"),
                title: rs.getString("title"),
                body: rs.getString("body")
              }));
          }
          rs.close();
          c.close();  
          return results;
        }
    
        throw new Error('could not connect to database');      
    };
    

提交回复
热议问题