zoukankan      html  css  js  c++  java
  • node读取MySQL数据

    var Client = require('mysql').createConnection({
        host:'127.0.0.1',
        user:'root',
        password:'root',
        database: 'angular',
        charset:'UTF8'
    })
    
    console.log('Connecting to MySQL...');
    
    http = require("http");
    
    var server = http.createServer(function(request, response) {
        response.writeHeader(200, {"Content-Type": "text/html;charset=utf-8"});
    
        Client.query('SELECT * FROM user', function selectCb(err, results, fields) {  
            if (err) {  
                throw err;  
            }  
    
            var data = '';
            for (var i=0; i<results.length; i++) {          
                var firstResult = results[i];
                data += 'id: ' + firstResult['id']+',name: ' + firstResult['name']+',age:'+firstResult['age']+',country:'+firstResult['country']; 
            } 
    
            response.write(data); 
            response.end();
        });
    });
    
    server.listen(8081);
    
    console.log("Server running at http://localhost:8081/"); 

     一、mysql中有数据库angular,angular库中有表user,user表中有四个字段:id,name,age和country

     二、当有中文时,如果不做任何处理就会出现乱码。因为,NodeJS 不支持 GBK。当然,UTF-8是支持的。所以,要确保不出现乱码:

     1.保证你的 JS文件是以UTF-8格式保存的。

     2. 在你的JS文件中的 writeHead 方法中加入 "charset=utf-8" 编码。

  • 相关阅读:
    阻止默认事件和冒泡
    js获取元素相对窗口位置
    ios中safari浏览器中date问题
    模拟单选框,多选框
    vue
    js合并两个对象的方法
    oracle 序列
    Oracle生成随机数大全
    JAVA基础面试题
    网速计算
  • 原文地址:https://www.cnblogs.com/iagw/p/6201611.html
Copyright © 2011-2022 走看看