简体   繁体   English

使用Groovy连接到MySQL

[英]Connecting to MySQL using Groovy

I'm trying to connect to a MySQL database using the below Groovy code on MAC OS 10.10.5 Yosemite 我正在尝试使用MAC OS 10.10.5 Yosemite上的以下Groovy代码连接到MySQL数据库

import groovy.sql.Sql

try{
    def dbURL = 'jdbc:mysql://localhost:3306/sakila'
    def dbUserName = 'root'
    def dbPassword = 'Orange@27'
    def dbDriver = 'com.mysql.jdbc.Driver'
    log.info('Good')
    def db = Sql.newInstance(dbURL,dbUserName,dbPassword,dbDriver)
}catch(Exception e){
    log.info('DB Error')
    log.info(e.getMessage())
}finally{

}

But when I execute this code, I see the below message 但是当我执行此代码时,我会看到以下消息

Sat Aug 13 15:09:14 EDT 2016:INFO:Good
Sat Aug 13 15:09:14 EDT 2016:INFO:DB Error
Sat Aug 13 15:09:14 EDT 2016:INFO:No suitable driver found for jdbc:mysql://localhost:3306/sakila

I have kept the groovy-sql-2.1.1.jar , mysql-connector-java-5.1.39-bin.jar inside the folder location /Applications/SoapUI-5.2.1/bin/ext/ 我把groovy-sql-2.1.1.jarmysql-connector-java-5.1.39-bin.jar在文件夹位置/Applications/SoapUI-5.2.1/bin/ext/

Could you please help me in resolving this issue? 你能帮我解决一下这个问题吗?

In order to use a JDBC driver you need to register it. 要使用JDBC驱动程序,您需要注册它。 There are a number of ways to do this: 有很多方法可以做到这一点:

Using DriverManager 使用DriverManager

You can register a JDBD driver with a DriverManager : 您可以使用DriverManager注册JDBD驱动程序:

import java.sql.DriverManager

DriverManager.registerDriver(new com.mysql.jdbc.Driver())

// Remaining Groovy code here

Class.forName 的Class.forName

Kind of a hack, but you can also dynamically load the driver's class: 有点hack,但你也可以动态加载驱动程序的类:

Class.forName('com.mysql.jdbc.Driver')

// Remaining Groovy code here

Groovy Grape Groovy葡萄

Because you're using Soap UI to run the Groovy code, this option may not work for you, but here it is for completeness: 因为您使用Soap UI来运行Groovy代码,所以此选项可能对您不起作用,但这里是为了完整性:

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

// Remaining Groovy code here
  • User libraries should be copied under SOAPUI_HOME/bin/ext directory, In this case, copy the mysql jdbc library in the above directory. 用户库应该在SOAPUI_HOME / bin / ext目录下复制,在这种情况下,复制上面目录中的mysql jdbc库。
  • SoapUI registers jdbc drivers differently. SoapUI以不同方式注册jdbc驱动程序。 Use below statement to register as per its documentation : 使用以下声明根据其文档进行注册:
//Register driver
com.eviware.soapui.support.GroovyUtils.registerJdbcDriver( "com.mysql.jdbc.Driver")
//Get the sql instance using the connection details.
Sql.newInstance(dbURL,dbUserName,dbPassword)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM