exports.main_handler = async (event, context, callback) => {var mysql = require('mysql2');var connection = mysql.createConnection({host : process.env.HOST,user : process.env.USER,password : process.env.PASSWORD});connection.connect();connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {if (error) throw error;console.log('The solution is: ', results[0].solution);});connection.end();}
key | value |
HOST | 数据库地址 |
USER | 数据库用户名 |
PASSWORD | 数据库密码 |
# -*- coding: utf8 -*-from os import getenvimport pymysqlfrom pymysql.err import OperationalErrormysql_conn = Nonedef __get_cursor():try:return mysql_conn.cursor()except OperationalError:mysql_conn.ping(reconnect=True)return mysql_conn.cursor()def main_handler(event, context):global mysql_connif not mysql_conn:mysql_conn = pymysql.connect(host = getenv('DB_HOST', '<YOUR DB HOST>'),user = getenv('DB_USER','<YOUR DB USER>'),password = getenv('DB_PASSWORD','<YOUR DB PASSWORD>'),db = getenv('DB_DATABASE','<YOUR DB DATABASE>'),port = int(getenv('DB_PORT','<YOUR DB PORT>')),charset = 'utf8mb4',autocommit = True)with __get_cursor() as cursor:cursor.execute('select * from employee')myresult = cursor.fetchall()print(myresult)for x in myresult:print(x)
'use strict';const DB_HOST = process.env[`DB_HOST`]const DB_PORT = process.env[`DB_PORT`]const DB_DATABASE = process.env[`DB_DATABASE`]const DB_USER = process.env[`DB_USER`]const DB_PASSWORD = process.env[`DB_PASSWORD`]const promisePool = require('mysql2').createPool({host : DB_HOST,user : DB_USER,port : DB_PORT,password : DB_PASSWORD,database : DB_DATABASE,connectionLimit : 1}).promise();exports.main_handler = async (event, context, callback) => {let result = await promisePool.query('select * from employee');console.log(result);}
<?phpfunction handler($event, $context) {try{$pdo = new PDO('mysql:host= getenv("DB_HOST");dbname= getenv("DB_DATABASE"),getenv("DB_USER"),getenv("DB_PASSWORD")');$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch(PDOException $e){echo '数据库连接失败: '.$e->getMessage();exit;}}
<?phpfunction main_handler($event, $context) {$host = "";$username = "";$password = "";
<dependencies><dependency><groupId>com.tencentcloudapi</groupId><artifactId>scf-java-events</artifactId><version>0.0.2</version></dependency><dependency><groupId>com.zaxxer</groupId><artifactId>HikariCP</artifactId><version>3.2.0</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.11</version></dependency></dependencies>
package example;import com.qcloud.scf.runtime.Context;import com.qcloud.services.scf.runtime.events.APIGatewayProxyRequestEvent;import com.qcloud.services.scf.runtime.events.APIGatewayProxyResponseEvent;import com.zaxxer.hikari.HikariConfig;import com.zaxxer.hikari.HikariDataSource;import javax.sql.DataSource;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.HashMap;import java.util.Map;public class Http {private DataSource dataSource;public Http() {HikariConfig config = new HikariConfig();config.setJdbcUrl("jdbc:mysql://" + System.getenv("DB_HOST") + ":"+ System.getenv("DB_PORT") + "/" + System.getenv("DB_DATABASE"));config.setUsername(System.getenv("DB_USER"));config.setPassword(System.getenv("DB_PASSWORD"));config.setDriverClassName("com.mysql.jdbc.Driver");config.setMaximumPoolSize(1);dataSource = new HikariDataSource(config);}public String mainHandler(APIGatewayProxyRequestEvent requestEvent, Context context) {System.out.println("start main handler");System.out.println("requestEvent: " + requestEvent);System.out.println("context: " + context);try (Connection conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM employee")) {ResultSet rs = ps.executeQuery();while (rs.next()) {System.out.println(rs.getInt("id"));System.out.println(rs.getString("first_name"));System.out.println(rs.getString("last_name"));System.out.println(rs.getString("address"));System.out.println(rs.getString("city"));}} catch (SQLException e) {e.printStackTrace();}APIGatewayProxyResponseEvent apiGatewayProxyResponseEvent = new APIGatewayProxyResponseEvent();apiGatewayProxyResponseEvent.setBody("API GW Test Success");apiGatewayProxyResponseEvent.setIsBase64Encoded(false);apiGatewayProxyResponseEvent.setStatusCode(200);Map<String, String> headers = new HashMap<>();headers.put("Content-Type", "text");headers.put("Access-Control-Allow-Origin", "*");apiGatewayProxyResponseEvent.setHeaders(headers);return apiGatewayProxyResponseEvent.toString();}}
'use strict';const database = require('scf-nodejs-serverlessdb-sdk').database;exports.main_handler = async (event, context, callback) => {let pool = await database('TESTDB2').pool()pool.query('select * from coffee',(err,results)=>{console.log('db2 callback query result:',results)})// no need to release poolconsole.log('db2 query result:',result)}
from serverless_db_sdk import databasedef main_handler(event, context):print('Start Serverlsess DB SDK function')connection = database().connection(autocommit=False)cursor = connection.cursor()cursor.execute('SELECT * FROM name')myresult = cursor.fetchall()for x in myresult:print(x)
scf-nodejs-serverlessdb-sdk
进行使用。
本页内容是否解决了您的问题?