การเชื่อมต่อฐานข้อมูลด้วย next.jdbc
เรียนรู้การสร้างการเชื่อมต่อฐานข้อมูลและดำเนินการคำสั่ง SQL โดยใช้ไลบรารี `next.jdbc`
การเชื่อมต่อฐานข้อมูลด้วย next.jdbc เป็นบทเรียน Clojure Functional Programming & JVM Backend Development ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Clojure Functional Programming & JVM Backend Development และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Clojure Functional Programming & JVM Backend Development มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Database Access in Clojure
Welcome to connecting Clojure with databases! Most real-world applications need to store and retrieve data, and databases are central to this.
In this lesson, you'll learn how to use next.jdbc, Clojure's popular library, to interact with various databases.
Meet next.jdbc
next.jdbc is a modern, idiomatic Clojure wrapper for JDBC (Java Database Connectivity). JDBC is the standard Java API for connecting to relational databases.
- It simplifies database operations.
- It provides a clean, functional interface.
- It's fast and efficient.
- It supports a wide range of databases (PostgreSQL, MySQL, H2, SQLite, etc.).
Adding Dependencies
Before we write any code, we need to add next.jdbc and a database driver to our project's dependencies. We'll use H2, an in-memory database, for easy examples.
Add these to your deps.edn file:
{:deps {org.clojure/clojure {:mvn/version "1.11.1"}
seancorfield/next.jdbc {:mvn/version "1.3.909"}
com.h2database/h2 {:mvn/version "2.2.220"}}}The Connection String (JDBC URL)
To connect to a database, you need a JDBC URL. This string tells next.jdbc (and the underlying JDBC driver) how to find and connect to your database.
For an in-memory H2 database, a common URL looks like this:
jdbc:h2:mem:testdb: Connects to an H2 database named 'testdb' in memory.jdbc:sqlite:my-data.db: Connects to a SQLite file.jdbc:postgresql://localhost/mydb: Connects to a PostgreSQL database.
Establishing a Datasource
A datasource is an object that represents a connection pool or factory for database connections. It's usually created once and reused.
next.jdbc's get-datasource function takes a map of connection parameters, including the JDBC URL.
Getting a Connection with <code>with-open</code>
After getting a datasource, you can obtain a connection. It's crucial to close connections after use to free up resources.
Clojure's with-open macro is perfect for this. It ensures that resources like database connections are automatically closed when they go out of scope.
Runnable: Connect & Disconnect
Let's see how to establish and close a database connection using next.jdbc and an in-memory H2 database. Run this code:
(ns my-app.core
(:require [next.jdbc :as jdbc]))
(defn -main
"Connects to an H2 in-memory database and closes the connection."
[]
(let [db-spec {:dbtype "h2" :dbname "mem:testdb"}]
(println "Attempting to connect...")
(with-open [conn (jdbc/get-connection db-spec)]
(println "Successfully connected to H2!\nConnection object:")
(println conn))
(println "Connection closed.")))
(-main)Executing Simple SQL Queries
Once connected, you can execute SQL queries. next.jdbc provides functions like jdbc/execute! for DDL (Data Definition Language) and DML (Data Manipulation Language) operations, and jdbc/execute-one! for queries expecting a single row result.
Queries are passed as vectors, with the SQL string followed by any parameters.
Runnable: Execute a Query
Now, let's create a table and insert some data into our in-memory H2 database, then query it. Notice how execute! returns a vector of maps.
(ns my-app.core
(:require [next.jdbc :as jdbc]))
(defn -main
"Connects, creates a table, inserts data, and queries it."
[]
(let [db-spec {:dbtype "h2" :dbname "mem:testdb"}]
(with-open [conn (jdbc/get-connection db-spec)]
(println "Connected. Creating table...")
(jdbc/execute! conn ["CREATE TABLE IF NOT EXISTS users (id INT PRIMARY KEY, name VARCHAR(255))"])
(println "Table created. Inserting data...")
(jdbc/execute! conn ["INSERT INTO users (id, name) VALUES (?, ?)" 1 "Alice"])
(jdbc/execute! conn ["INSERT INTO users (id, name) VALUES (?, ?)" 2 "Bob"])
(println "Data inserted. Querying data...")
(let [result (jdbc/execute! conn ["SELECT id, name FROM users"])]
(println "Query Result:")
(doseq [row result] (println row))))
(println "Operations complete. Connection closed.")))
(-main)Quick Check on Connections
What is the primary purpose of using with-open when dealing with database connections in Clojure?
Recap: Connecting to Databases
You've taken the first step into database interaction with Clojure!
- We introduced
next.jdbcas a powerful library for database access. - You learned how to add necessary dependencies (
next.jdbcand a JDBC driver like H2). - We covered JDBC URLs and how to establish a datasource and connection.
- You saw how
with-openensures connections are properly managed. - Finally, we executed basic DDL and DML queries using
jdbc/execute!.
Next, we'll dive deeper into CRUD operations!
คำถามที่พบบ่อย
บทเรียน “การเชื่อมต่อฐานข้อมูลด้วย next.jdbc” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การเชื่อมต่อฐานข้อมูลด้วย next.jdbc” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Clojure Functional Programming & JVM Backend Development ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Clojure Functional Programming & JVM Backend Development มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การเชื่อมต่อฐานข้อมูลด้วย next.jdbc”
เรียนรู้การสร้างการเชื่อมต่อฐานข้อมูลและดำเนินการคำสั่ง SQL โดยใช้ไลบรารี `next.jdbc` คุณปฏิบัติ Clojure Functional Programming & JVM Backend Development ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Clojure Functional Programming & JVM Backend Development หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Clojure Functional Programming & JVM Backend Development บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “การเชื่อมต่อฐานข้อมูลด้วย next.jdbc” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Clojure Functional Programming & JVM Backend Development นี้ได้ไหม
ได้ บทเรียน Clojure Functional Programming & JVM Backend Development ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การเชื่อมต่อฐานข้อมูลด้วย next.jdbc
- การดำเนินการสร้าง อ่าน ปรับปรุง และลบข้อมูล
- การย้ายฐานข้อมูลและการจัดการสคีมา
- การจัดกลุ่มการเชื่อมต่อและธุรกรรม