开发者社区> 问答> 正文

node.js怎么向mysql数据库插入数据,菜鸟求救?报错

这个是网上找的,但是运行报错!!TypeError: client.connect is not a function
有没有运行成功的给个demo呢?谢谢!!

var util = require('util');

var Client = require('/Users/Administrator/AppData/Roaming/npm/node_modules/mysql').Client;
var client = new Client();
  
client.user = 'root';
client.password = 'w123456';
  
console.log('Connecting to MySQL...');
  
client.connect(function(error, results) {
  if(error) {
    console.log('Connection Error: ' + error.message);
    return;
  }
  console.log('Connected to MySQL');
  ClientConnectionReady(client);
});
  
ClientConnectionReady = function(client)
{
    client.query('USE mvc1', function(error, results) {
        if(error) {
            console.log('ClientConnectionReady Error: ' + error.message);
            client.end();
            return;
        }
        ClientReady(client);
    });
};
  
ClientReady = function(client)
{
  var values = ['Chad', 'Lung', 'Hello World'];
  client.query('INSERT INTO MyTable SET firstname = ?, lastname = ? , message = ?', values,
    function(error, results) {
      if(error) {
        console.log("ClientReady Error: " + error.message);
        client.end();
        return;
      }
      console.log('Inserted: ' + results.affectedRows + ' row.');
      console.log('Id inserted: ' + results.insertId);
    }
  );
  GetData(client);
}
  
GetData = function(client)
{
  client.query(
    'SELECT * FROM MyTable',
    function selectCb(error, results, fields) {
      if (error) {
          console.log('GetData Error: ' + error.message);
          client.end();
          return;
      }
      // Uncomment these if you want lots of feedback
      //console.log('Results:');
      //console.log(results);
      //console.log('Field metadata:');
      //console.log(fields);
      //console.log(sys.inspect(results));
  
      if(results.length > 0)
      {
        var firstResult = results[0];
        console.log('First Name: ' + firstResult['firstname']);
        console.log('Last Name: ' + firstResult['lastname']);
        console.log('Message: ' + firstResult['message']);
      }
  });
  
  client.end();
  console.log('Connection closed');
};

---------------------------------------------------------------------------------------------------------------
//var uname="王五";
//var pwd="123";
//var value0=["王五","123"];
//var sql="insert into u_user set name=?,password=?";add(sql,value0,callback)
//var sql='insert into u_user(name,password) values(uname,pwd)';
//var sql='insert into u_user(name,password) values('+uname+','+pwd+')';
var sql='select * from u_user';
//var sql='insert into u_user(name,password) values("张思","123")';
function d(){
add(sql,function(err,result){
   if(err){
   console.log('err');
   }else{
   console.log('yes');
   }
    })
}
d();

//console.log(pw);
//连接数据库
function add(sql,callback){
var mysql=require('/Users/Administrator/AppData/Roaming/npm/node_modules/mysql');
    var conn=mysql.createConnection({
  'host':'localhost',
  'user':'root',
  'password':'w123456',
    });
    conn.connect();
conn.query('use mvc1');
    conn.query(sql,function(err,result){
if(err){
return callback(err,err);
}else{
return callback(null,result);
}

    });
    conn.end();
}

查找什么的没问题,插入就有问题,sql语句换来换去没搞定

展开
收起
爱吃鱼的程序员 2020-06-09 13:43:50 912 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    varsql='insertintou_usersetname=?,passward=?';
    varvalues=['王娜','4589'];


    //连接数据库
    varmysql=require('/Users/Administrator/AppData/Roaming/npm/node_modules/mysql');
    varconn=mysql.createConnection({
    'host':'localhost',
    'user':'root',
    'password':'w123456',
    });
    conn.connect();
    conn.query('usemvc1');

    conn.query(sql,values,function(err,result){
    if(err){
    console.log(err);
    }else{
    console.log(result.insertId);
    }

    });
    conn.end();

    --------复杂的----
    //varutil=require('util');
      
    varmysql=require('/Users/Administrator/AppData/Roaming/npm/node_modules/mysql');
    varconn=mysql.createConnection({
     'host':'localhost',
     'user':'root',
     'password':'w123456',
    });
      
    console.log('ConnectingtoMySQL...');
      
    conn.connect(function(error,results){
     if(error){
      console.log('ConnectionError:'+error.message);
      return;
     }
     console.log('ConnectedtoMySQL');
     ConnectionReady(conn);
    });
      
    ConnectionReady=function(conn)
    {
      conn.query('USEmvc1',function(error,results){
        if(error){
          console.log('ConnectionReadyError:'+error.message);
          conn.end();
          return;
        }
        ConnReady(conn);
      });
    };
      
    ConnReady=function(conn)
    {
     varvalues=['Chd1','Lung','HelloWorld'];
     conn.query('INSERTINTOMyTableSETfirstname=?,lastname=?,message=?',values,
      function(error,results){
       if(error){
        console.log("ConnReadyError:"+error.message);
        conn.end();
        return;
       }
       console.log('Inserted:'+results.affectedRows+'row.');
       console.log('Idinserted:'+results.insertId);
      }
     );
     GetData(conn);
    }
      
    GetData=function(conn)
    {
     conn.query(
      'SELECT*FROMMyTable',
      functionselectCb(error,results,fields){
       if(error){
         console.log('GetDataError:'+error.message);
         conn.end();
         return;
       }  
      
       if(results.length>0)
       {
        varfirstResult=results[0];
        console.log('FirstName:'+firstResult['firstname']);
        console.log('LastName:'+firstResult['lastname']);
        console.log('Message:'+firstResult['message']);
       }
     });
      
     conn.end();
     console.log('Connectionclosed');
    };

    已解决推荐资料:<atarget="_blank"rel="nofollow">http://edu.51cto.com/course/course_id-4437.html谢了,已搞定

    2020-06-09 13:44:09
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
搭建电商项目架构连接MySQL 立即下载
搭建4层电商项目架构,实战连接MySQL 立即下载
PolarDB MySQL引擎重磅功能及产品能力盛大发布 立即下载

相关镜像