跳转到主要内容

如何使用 Node.js 与 Databend 交互

准备工作

创建 Databend 用户

mysql -h127.0.0.1 -uroot -P3307

创建用户

CREATE USER user1 IDENTIFIED BY 'abc123';

授予权限

Grants ALL privileges to the user user1:

GRANT ALL ON *.* TO user1;

Node.js

本指南将会展示如何使用 Node.js 连接 Databend 并执行查询。

我们将创建一个名为 books 的表并插入一行数据,然后进行查询。

npm install --save mysql
databend.js
const mysql = require('mysql');
const con = mysql.createConnection({
host: 'localhost',
port: 3307,
user: 'user1',
password: 'abc123',
});

con.connect((err) => {
if (err) throw err;
console.log('Connected to Databend Server!');

var sql = "CREATE DATABASE IF NOT EXISTS book_db";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Dataabse created");
});

var sql = "USE book_db";
con.query(sql, function (err, result) {
if (err) throw err;
});


var sql = "CREATE TABLE IF NOT EXISTS books(title VARCHAR, author VARCHAR, date VARCHAR)";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});

var sql = "INSERT INTO books VALUES('mybook', 'author', '2022')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});

con.query("SELECT * FROM books", function (err, result, fields) {
if (err) throw err;
console.log(result);
});

});

运行 nodejs databend.js:

Connected to Databend Server!
Dataabse created
Table created
1 record inserted
[ RowDataPacket { title: 'mybook', author: 'author', date: '2022' } ]