Reputation: 5091
I'm trying out Gradle and JDBC for the first time. I have the following gradle.build file:
apply plugin: 'java-library'
apply plugin: 'java'
repositories {
jcenter()
mavenCentral()
}
dependencies {
compile 'mysql:mysql-connector-java:5.1.36'
testImplementation 'junit:junit:4.12'
}
In my HelloMySQL.java file, I'm trying to establish a connection to the MySQL database WORLD
(Verified the URL and port). I have the following code:
package Hello;
import java.sql.*;
public class HelloMySQL {
public static void main(String[] args) {
Connection conn = null;
try{
System.out.println("Trying to connect...");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/WORLD", "root", "root");
System.out.println("Creating statement...");
Statement stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM City LIMIT 10";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String countryCode = rs.getString("CountryCode");
System.out.println(id + " " + name + "\t " + countryCode);
}
} catch(SQLException e){
System.out.println(e.toString());
}
}
}
I've also tried adding this line before the DriverManager.getConnection
:
Class.forName('com.mysql.jdbc.Driver');
but it throws a java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Am I doing something wrong with the gradle build file?
EDIT: I have not added the jar for MySQL connector to the project. Gradle will download it for me, right?
Upvotes: 0
Views: 2627
Reputation: 5091
I found the problem. Not exactly a problem but still posting it for people who might struggle with Eclipse.
After you make changes to the gradle.build
file, Cleaning the project won't do. You'll need to refresh the gradle project as well.
Right click in the build.gradle file -> Gradle -> Refresh Gradle Project
Upvotes: 1