我用Java编写了一个简单的程序,该程序打开与oracle数据库的连接,然后关闭连接。
我将gradle设置为香草项目。这是我的build.gradle
文件:
plugins {
id 'java'
id 'application'
id 'maven'
}
repositories {
jcenter()
mavenLocal()
}
dependencies {
implementation 'com.google.guava:guava:26.0-jre'
implementation 'com.oracle:ojdbc8:19.3'
testImplementation 'junit:junit:4.12'
}
// Define the main class for the application
mainClassName = 'lab2.jdbc.App'
jar {
manifest {
attributes(
'Class-Path': configurations.compile.collect { it.getName() }.join(' '),
'Main-Class': 'lab2.jdbc.App'
)
}
}
这是我的主班:
package lab2.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class App {
public static void main(String[] args) {
Properties props = new Properties();
props.put("user", "user");
props.put("password", "password");
try {
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", props);
System.out.println("Successfully connected!");
try {
connection.close();
System.out.println("Successfully disconnected");
} catch (SQLException e) {
System.out.println("Failed to disconnect: " + e);
}
} catch (SQLException e) {
System.out.println("Failed to connect: " + e);
}
}
}
[当我使用任务run
运行项目时,它运行正常:
> Task :run
Successfully connected!
Successfully disconnected
BUILD SUCCESSFUL in 6s
2 actionable tasks: 2 executed
但是当我尝试运行jar时,它不起作用:
./gradlew jar
java -jar build/libs/lab2-jdbc.jar
Failed to connect: java.sql.SQLException: No suitable driver found for jdbc:oracle:thin:@localhost:1521:XE
怎么了?
build.gradle
文件存在两个问题:
1)Oracle JDBC依赖项应为:
implementation 'com.oracle.ojdbc:ojdbc8:19.3.0.0'
2)您不包括创建胖罐子的类路径依赖项。为此,您需要更改以下内容:
jar {
manifest {
attributes(
'Main-Class': 'lab2.jdbc.App'
)
}
from {
configurations.compileClasspath.filter { it.exists() }.collect { it.isDirectory() ? it : zipTree(it) }
}
}