mysql - 如何从 Clojure 连接到 MySQL 数据库?

标签 mysql clojure

假设:您的机器上已经同时运行了 Clojure 和 MySQL。
你如何让他们说话?

最佳答案

假设:您的机器上已经同时运行 Clojure 和 MySQL。

  1. checkout 和构建 clojure-contrib :

    git clone git://github.com/richhickey/clojure-contrib.git
    cd clojure-contrib
    build
    

    将生成的 clojure-contrib.jar 放入您的 CLASSPATH

  2. 下载MySQL Connector/J并将 mysql-connector-java-5.1.7-bin.jar 放在您的 CLASSPATH

    您可能必须使用以下参数运行 JVM:

    -Djdbc.drivers=com.mysql.jdbc.Driver
    
  3. 确定 MySQL 数据库的连接 URL

    例如,如果您在 MAMP 下运行 MySQL那么您将在 JDBC 中使用的 URL 将类似于:

    conn = DriverManager.getConnection
            ("jdbc:mysql://localhost:8889/db_name?user=root&password=root")
    

    url被分解成这些组件:

    • 协议(protocol):jdbc:
    • 子协议(protocol):mysql
    • db-host: localhost
    • 数据库端口:8889
    • 用户名
    • 密码
  4. 制作这个clojure脚本,修改数据库连接参数匹配你的URL,另存为test.clj,编译运行。

    (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 编写的类似代码到 access a Postgres database from Clojure

关于mysql - 如何从 Clojure 连接到 MySQL 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/613929/

相关文章:

php - 如何在 MySQL 和 PHP 中找到相同的表?

mysql - 如何在 phpMyAdmin 中临时禁用数据库

clojure - 使用 enlive 解析 html 片段

java - 您如何在 eclipse 中设置一个 clojure 项目,以便在您单击运行时启动它?

macros - 非法状态异常 : Attempting to call unbound fn in macro

css - 重复的花园语法

c# - SQL C# insert 命令不起作用

mysql - 带有 union 和 order by 的 sql 语句

java - Sun 对 Clojure 的态度如何?

php - SQL-JOIN 错误 => 多个表中的相同列名