Install all packages:
# apt-get install openjdk-8-jdk libmysql-java libpostgresql-jdbc-java libpostgresql-jdbc-java-doc
Note: openjdk-8-jdk requires backports repository, add this into /etc/apt/sources.list
deb http://ftp.de.debian.org/debian jessie-backports main
To set Java Environment for all users, add/edit /etc/environment:
JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64"
CLASSPATH=".:/usr/share/java/mysql.jar:/usr/share/java/postgresql-jdbc4.jar"
Note: if you prefered to use postgresql-jdbc3, replace /usr/share/java/postgresql-jdbc4.jar with /usr/share/java/postgresql.jar
Example Java code loading MySQL:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
class TestDB {
/*
/usr/share/java
http://dev.mysql.com/doc/connector-j/5.1/en/
https://jdbc.postgresql.org/documentation/documentation.html
*/
static Connection conn = null;
public static void main(String[] args) {
// MySQL
try {
System.out.println("Loading Class com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver") ;
System.out.println("Loading com.mysql.jdbc.Driver Successful");
conn = DriverManager.getConnection("jdbc:mysql://localhost/database?user=user&password=password");
// Do something with the Connection
System.out.println("Test Connection Successful");
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} catch (ClassNotFoundException ex) {
System.out.println("Class Not Found: " + ex.getMessage());
}
// PostgreSQL
try {
System.out.println("Loading Class org.postgresql.Driver");
Class.forName("org.postgresql.Driver");
System.out.println("Loading org.postgresql.Driver Successful");
String url = "jdbc:postgresql://localhost/database";
Properties props = new Properties();
props.setProperty("user","user");
props.setProperty("password","password");
props.setProperty("ssl","true");
conn = DriverManager.getConnection(url, props);
// or
url = "jdbc:postgresql://localhost/database?user=user&password=password&ssl=true";
Connection conn = DriverManager.getConnection(url);
// Do something with the Connection
System.out.println("Test Connection Successful");
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} catch (ClassNotFoundException ex) {
System.out.println("Class Not Found: " + ex.getMessage());
}
}
}
References:
No comments:
Post a Comment