Reputation: 999
I have defined my postgres database as
(def db {:subprotocol "postgresql"
:subname "//localhost:5432/mydb"
:user "admin"
:password "password"})
I have also defined a function
(defn get-users []
(sql/query db ["select * from users"]))
where sql is [clojure.java.jdbc :as sql]
If I run (get-users)
I get the error
SQLException No suitable driver found for jdbc:postgresql://127.0.0.1:5432/mydb java.sql.DriverManager.getConnection (DriverManager.java:689)
I've seen from other Java posts that I need to load the driver using Class.forName("org.postgresql.Driver");
1) What does this mean?
2) How do I do this/solve my error in Clojure?
Upvotes: 2
Views: 2264
Reputation: 4816
The solution is to add this to your :dependencies
in your project.clj:
[org.postgresql/postgresql "42.1.4"]
Also, while your db definition is fine, instead of the concatenated string for :subname
, you can also separately define the host, port, and db name, which makes it more modular and composable in case any one of them changes:
(def db {:dbtype "postgresql"
:dbname "mydb"
:host "localhost"
:port 5432
:user "userrole"
:password "password"})
Upvotes: 7
Reputation: 6509
This means that the JVM needs to have loaded the Postgres driver class before the driver can be used. The sql/query
call uses the driver. Usually in Java classes are instantiated, so the class is automatically loaded. But notice that your code has no new
, nor is a static factory (constructor) method called. With the call to sql/query
you are in fact directly calling the function java.sql.DriverManager.getConnection
, without the class DriverManager
ever having been loaded. Presumably loading Driver
loads DriverManager
.
From http://clojure-doc.org/articles/language/interop.html I found this:
(Class/forName "java.util.Date")
So you could try:
(Class/forName "org.postgresql.Driver")
Upvotes: 1