Обязательно следуйте инструкциям на Подключение к облачному SQL из App Engine . В частности, легко упустить следующие вещи:
- Убедитесь, что подключение вашей учетной записи службы имеет роль
Cloud SQL Client
IAM или разрешения, указанные на странице - При использовании приложенияEngine Flex, убедитесь, что вы правильно написали его на
app.yaml
Наконец, обязательно посмотрите на страницу Управление соединениями с базой данных . В частности, в приведенном выше примере вы инициализируете функцию с именем, а затем вызываете запрос для этой функции. Вместо этого вы должны использовать пул для выполнения ваших запросов:
let pool; // <---- This is the pool that `createPool` will set
const createPool = async () => {
pool = await mysql.createPool({
socketPath:"/cloudsql/idyllic-anvil-256103:asia-south1:database",
user: "abc@gmail.com", //<--- just FYI, this should be the database user, not the GCP account connecting
password: "pass",
database: "db"
});
};
createPool(); // <----- This is where `pool` is actually created
// Now we can use the pool to query like this:
try {
const stmt = 'INSERT INTO votes (time_cast, candidate) VALUES (?, ?)';
// Pool.query automatically checks out, uses, and releases a connection
// back into the pool, ensuring it is always returned successfully.
await pool.query(stmt, [timestamp, team]);
} catch (err) {
// If something goes wrong, handle the error in this section. This might
// involve retrying or adjusting parameters depending on the situation.
// ...
}