Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No suitable driver found when connected to mysql in groovy

Tags:

mysql

groovy

jdbc

    import com.mysql.jdbc.jdbc2.optional.MysqlDataSource
    import com.mysql.jdbc.*
    import groovy.sql.*

    /*  the commented code works fine

    MysqlDataSource ds = new MysqlDataSource()
    ds.user = 'root'
    ds.password = ""
    ds.url = 'jdbc:mysql://localhost:3306/test'

    Sql sql=Sql.newInstance(ds)

    sql.close()
    */
    d=Class.forName("com.mysql.jdbc.Driver").newInstance()
    println d.class // class com.mysql.jdbc.Driver


    Sql sql=Sql.newInstance(
    'jdbc:mysql://localhost:3306/test',
    'root',
     "",
    'com.mysql.jdbc.Driver'
    )

the code commented works fine and I can get the instance of Driver
But when I use the

     Sql sql=Sql.newInstance(
     'jdbc:mysql://localhost:3306/test',
     'root',
      "",
     'com.mysql.jdbc.Driver'
     )

it throws a exception: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test
I can not fix it ,is there anyboy coming to help me?

like image 200
fairjm Avatar asked Dec 19 '13 12:12

fairjm


People also ask

How do I fix no suitable driver found for jdbc mysql?

This error occurs if JDBC is not able to find a suitable driver for the URL format passed to the getConnection() method e.g. "jdbc:mysql://" in our case. In order to solve this error, you need the MySQL JDBC driver like mysql-connector-java-5.1. 36. jar in your classpath.

What is JDBC URL for mysql?

URL for Connection:- The connection URL for the mysql database is jdbc:mysql://localhost:3306/mydb ('mydb' is the name of database).

How do I add mysql connector jar to classpath?

After extracting the distribution archive, you can install the driver by placing MySQL-connector-java-version-bin. jar in your classpath, either by adding the full path to it to your classpath environment variable or by directly specifying it with the command line switch -cp when starting the JVM.


1 Answers

The JDBC driver management in Java looks at the system classloader for the JDBC jars.

So to run a mysql accessing script in the GroovyConsole, you either need to use:

@GrabConfig( systemClassLoader=true )
@Grab( 'mysql:mysql-connector-java:5.1.27' )

in your script, or you need to start the console with the jar on the classpath by running it with:

groovyconsole -cp mysql-connector-java-5.1.27-bin.jar

I don't think there's a way to tell the add jars to path option to use the systemClassLoader :-(

like image 113
tim_yates Avatar answered Oct 13 '22 19:10

tim_yates