我想连接到clouds-sql数据库,从数据库中的表中获取数据,并在html网页中显示值。我无法验证这是否有效,因为控制台日志不适用于我。我如何在网页上显示结果。
const mysql = require('mysql');
function connectToDatabase() {
cost connection = mysql.createConnection({
host: '10.60.33.4'
user: 'root',
password: 'admin@1222',
database: 'portal'
});
return new Promise((resolve, reject) => {
connection.connect(; resolve(connection);
});
} {
function queryDatabase(connection)
return new Promise((resolve, reject) => {
connection.query('SELECT *
FROM job_description ', (error, results,
fields) => {
resolve(results);
});
});
function handlesql(){
return connectToDatabase()
then(connection => {
return queryDatabase(connection)
then(result => {
res = result;
connection.end():
})
}
exports.helloWorld = (req, res) => {
handlesql();
let message = req.query.message || req.body.message || res;
res.status(200).send(message);
};
您可以从各种可用的选项中进行选择,以连接到云SQL,如使用云运行、云函数、应用程序引擎等。请查看SQL Connect的文档
一旦您确定了要继续连接到云SQL实例的方法,请完成云SQL实例设置
由于您的代码使用的是node js Cloud Functions,请检查以下代码片段以验证详细信息。
// createUnixSocketPool initializes a Unix socket connection pool for
// a Cloud SQL instance of MySQL.
const createUnixSocketPool = async config => {
// Note: Saving credentials in environment variables is convenient, but not
// secure - consider a more secure solution such as
// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help
// keep secrets safe.
return mysql.createPool({
user: process.env.DB_USER, // e.g. 'my-db-user'
password: process.env.DB_PASS, // e.g. 'my-db-password'
database: process.env.DB_NAME, // e.g. 'my-database'
socketPath: process.env.INSTANCE_UNIX_SOCKET, // e.g. '/cloudsql/project:region:instance'
// Specify additional properties here.
...config,
});
};
此外,我建议您查看Git Hub链接,了解更多信息和相关方法。