我无法从Gradle构建中获取.jar以使用JDBC MySQL连接器连接到远程数据库。我收到ClassNotFoundException,这使我相信.jar不在类路径中。我是Gradle的新手,所以我一直在尝试修改在新的Eclipse项目中创建的默认build.gradle。
Java对象:
package com.blu.generator;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class MySQLConnection {
private Connection _conn;
// init
MySQLConnection(String url, String user, String pass) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.cj.jdbc.Driver");
this._conn = DriverManager.getConnection(url, user, pass);
System.out.println("Database connection established.");
}
public void getDrugsClaims() throws SQLException {
String query = "select * from drugs";
Statement st = this._conn.createStatement();
ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (rs.next()) {
//Print one row
for(int i = 1 ; i <= columnsNumber; i++){
System.out.print(rs.getString(i) + " ");
}
System.out.println();
}
return;
}
}
build.gradle:
apply plugin: 'java-library'
// In this section you declare where to find the dependencies of your project
repositories {
// Use jcenter for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
}
configurations {
driver
}
dependencies {
// This dependency is exported to consumers, that is to say found on their compile classpath.
api 'org.apache.commons:commons-math3:3.6.1'
// This dependency is used internally, and not exposed to consumers on their own compile classpath.
implementation 'com.google.guava:guava:23.0'
// Use JUnit test framework
testImplementation 'junit:junit:4.12'
// this is for mysql java connector
compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.15'
runtime "mysql:mysql-connector-java:8.0.15"
}
jar {
manifest {
attributes(
'Main-Class': 'com.blu.generator.Main'
)
}
}
答案 0 :(得分:1)
我相信您的导入工作正常,但是您用Class.forName
调用了错误的名称。代替Class.forName("com.mysql.cj.jdbc.Driver");
,它应该是Class.forName("com.mysql.jdbc.Driver");