This sample Java program connects to MySQL database using JDBC, executes a query and retrieves and prints the value of the database field.
This same sample code can be used to connect to any type of database, all you need to do is change the connection url (dbUrl in the sample). For this code to work properly, you will need to download the mysql driver for JDBC in other words Java Connectors from mysql.com site.
If after downloading the URL it still doesn't work then it is probably due to the classpath. You will have to add the driver jar file in the classpath.
import java.sql.*;
import javax.sql.*;
public class jdbcdemo{
public static void main(String args[]){
String dbtime;
String dbUrl = "jdbc:mysql://your.database.domain/yourDBname";
String dbClass = "com.mysql.jdbc.Driver";
String query = "Select * FROM users";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (dbUrl);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
dbtime = rs.getString(1);
System.out.println(dbtime);
} //end while
con.close();
} //end try
catch(ClassNotFoundException e) {
e.printStackTrace();
}
catch(SQLException e) {
e.printStackTrace();
}
} //end main
} //end class