Using a simple example online, I am running a Java program to return users from a table.
The database is MySQL. I have already downloaded the JDBC driver, stored it in my JRE7 /lib folder.
The problem is the program never connects to the database, it skips the whole try block and prints out a "test" string at the end. Have I overlooked a major step in this? It's really frustrating!!
EDIT: Best to describe how I've attempted to set up a connection to the database.
The mysql-connector-java-5.1.18-bin is stored in jre7/lib.
I startup mysql workbench. The connection is name ive created is com.fyp.db, with the host address at 127.0.0.1:3306.
I then run my code, which attempts to query the sample table - sakila - provided by mySQL workbench and..nothing!
Installed MySQL workbench. Installed JDBC driver.
public class Version {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
//String url = "jdbc:mysql://127.0.0.1/sakila";
String url = "jdbc:mysql://localhost:3306/sakila";
String user = "root";
String password = "root";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("select * from ACTOR;");
System.out.println("test");
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
It is simple .. you need .jar file called mysql-connector-java-5.1.16-bin.jar ,,, download it and add it to your libs ...
good luck !!!
I think you need this line:
Class.forName("org.mysql.Driver");
before calling DriverManager.getConnection(...);
You probably should create new driver instance. Here's how:
Class.forName("com.mysql.jdbc.Driver").newInstance();
You need to ensure that the jdbc.drivers
property is set. There are a variety of ways to do this,
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.