如何从 Clojure 连接到 MySQL 数据库?
假设:您的机器上已经运行了 Clojure 和 MySQL.
你如何让他们说话?
Assumption: you already have both Clojure and MySQL running on your machine.
How do you make them talk?
推荐答案
假设:您的机器上已经同时运行了 Clojure 和 MySQL.
Assumption: you already have both Clojure and MySQL running on your machine.
签出并构建clojure-contrib:
git clone git://github.com/richhickey/clojure-contrib.git
cd clojure-contrib
build
将生成的 clojure-contrib.jar 放在您的 CLASSPATH 中.
Put the resulting clojure-contrib.jar on your CLASSPATH.
下载MySQL 连接器/J 并将 mysql-connector-java-5.1.7-bin.jar 放在您的 CLASSPATH
Download MySQL Connector/J and put the mysql-connector-java-5.1.7-bin.jar on your CLASSPATH
您可能必须使用以下参数运行 JVM:
-Djdbc.drivers=com.mysql.jdbc.Driver
确定您的 MySQL 数据库的连接 URL
Determine the connection URL of your MySQL database
例如,如果您在 MAMP 下运行 MySQL,那么您将在 JDBC 中使用的 URL 将如下所示类似:
For example, if you are running MySQL under MAMP then the URL that you would use in JDBC will look something like:
conn = DriverManager.getConnection
("jdbc:mysql://localhost:8889/db_name?user=root&password=root")
网址分为以下几个部分:
The url is broken down into these components:
- 协议:
jdbc:
- 子协议:
mysql
- db-host:
localhost
- 数据库端口:
8889
- 用户名
- 密码
制作这个clojure脚本,修改数据库连接参数以匹配你的URL,保存为test.clj,编译运行.
Make this clojure script, modify the database connection parameters to match your URL, save as test.clj, compile and run.
(use 'clojure.contrib.sql) ;;' satisfy prettify
(let [db-host "localhost"
db-port 8889
db-name "db_name"]
(def db {:classname "com.mysql.jdbc.Driver"
:subprotocol "mysql"
:subname (str "//" db-host ":" db-port "/" db-name)
:user "root"
:password "root"})
(with-connection db
(with-query-results rs ["select * from languages"]
(dorun (map #(println (:language :iso_code %)) rs)))))
; rs will be a sequence of maps,
; one for each record in the result set.
NB 此代码改编自 Mark Volkmann 编写的类似代码 从 Clojure 访问 Postgres 数据库
NB This code was adapted from similar code written by Mark Volkmann to access a Postgres database from Clojure
相关文章