0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【TypeScript】Neon Database に接続、SQL実行

Last updated at Posted at 2025-08-15

パッケージインストール

npm を使っているなら、以下でインストール

npm i @neondatabase/serverless

サンプルコード

ほぼ公式ドキュメント通りです

import { neon } from '@neondatabase/serverless';

// neon DB へ接続
// process.env.DATABASE_URL で .env に書かれた neon への接続文字列を取得
const sql = neon(process.env.DATABASE_URL);

const postId = 1;

// sql.query() で SQL 実行
const rows = await sql.query('SELECT * FROM schema_name.table_name WHERE id = $1', [postId]);
console.log(rows); // 取得結果は配列

実装としては、neon接続 → SQL 実行なので、insert, update でも同様に実装できます。
(PostgreSQL の schema 指定が必要な際も、SQL内で指定する)

接続文字列の発行

サンプルコード内の process.env.DATABASE_URLに当てはめる接続文字列の発行は、以下手順で行えます

1.「Dashboard」画面内の「Connect」を押下
image.png

2.ポップアップしたウィンドウで接続先の環境情報をセットし、「Copy snippet」を押下する
→ クリップボードに貼り付けられた文字列をprocess.env.DATABASE_URLに当てはめることでTypeScriptのコードから実際にSQLを実行できる様になります。

image.png

公式ドキュメント

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?