【问题标题】:How to connect an action on IBM Cloud Functions with a database?如何将 IBM Cloud Functions 上的操作与数据库连接起来?
【发布时间】:2019-03-20 22:14:37
【问题描述】:

我在 watson 助手中进行了一次对话,我希望能够从 IBM 云函数中调用一个操作来对我的数据库 (Azure) 进行一些查询。我不熟悉云功能,所以这可能是一个愚蠢的问题,我不明白如何与数据库建立连接,我尝试编写一些 nodejs 代码但我当然错了,因为它返回“内部错误” ”。 我还尝试用 python 而不是 nodejs 编写一些代码。 这又是一个愚蠢的问题,所以请原谅我。谢谢!

    var mysql = require('mysql');

    var connection = mysql.createConnection({
      host: 'my_host',
      user: 'my_user',
      password: 'my_psw',
      database: 'my_db'
    });

    connection.connect();

    rows = connection.query('my_query')
    if (!err) {
      console.log(typeof(rows));
      console.log('The solution is: ', rows);
    } else {
      console.log(typeof(rows));
      console.log('Error while performing Query.');

    }


    connection.end();

{
  "error": "Internal error."
}

import pyodbc as pyodbc

conn = pyodbc.connect('DRIVER={SQL Server};SERVER=my_server;DATABASE=my_db;UID=my_user;PWD=my_pwd')
cursor = conn.cursor()
sql = "my_sql" 
cursor.execute(sql)
result = cursor.fetchall()
print(result)


csr = conn.cursor()
csr.close()
del csr
conn.close()
    

{
  "error": "The action did not return a dictionary."
}

【问题讨论】:

标签: node.js sql-server ibm-cloud watson-conversation ibm-cloud-functions


【解决方案1】:

错误来自您返回结果的方式。您需要将结果打包成有效的 JSON 结构。

return {"sqlresult": myresult}

我在上面的评论中引用了两个教程。 chatbot tutorial 使用 Node.js 来实现 Cloud Functions。这些函数是从 Watson Assistant 调用的。 Take a look at this action that fetches records from a Db2 database。它打开一个数据库连接,获取记录并将它们打包成一个 JSON 结构。然后将该 JSON 对象返回给 Watson Assistant。

本教程还展示了如何将数据库凭据传递到 Cloud Function。

【讨论】:

    猜你喜欢
    • 2018-06-14
    • 2018-08-05
    • 2020-06-03
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 2018-06-09
    相关资源
    最近更新 更多