I am trying to set up a remote Derby database just for practice. The following code works without a problem whenever I access the DB on my harddrive:
class Test{
public static void main(String[] args) {
String protocol = "jdbc:derby:";
// String dbPath = "C:/Java_Practice/derbyDB"; // this dbPath works...
String dbPath = "//108.167.141.127/derbyDB"; // and this one doesn't
String url = protocol + dbPath;
try( Connection conn = DriverManager.getConnection(url) )
{
System.out.println(conn);
}
catch(SQLException e){
System.out.println(e.getMessage());
}
}
}
I then uploaded the whole derbyDB directory to my Hostgator-hosted website, obtained its IP by pinging the server and edited the dbPath var accordingly. The code stopped working as if it can't even see the DB. What am I missing?
Looks like your driver class not loaded.
Try loading it before calling DriverManager.getConnection, and see if it works.
String driver = "org.apache.derby.jdbc.ClientDriver";
Class.forName(driver).newInstance();
String protocol = "jdbc:derby:";
String dbPath = "//108.167.141.127/derbyDB"+";create=true";
String url = protocol + dbPath;
Connection conn = DriverManager.getConnection(url);
Answering my own question after some digging.
This is what I found in the official Apache Derby documentation (https://db.apache.org/derby/docs/10.0/manuals/develop/develop14.html):
You can specify only databases that are local to the machine on which
the JVM is running.
Looks like what I wanted to accomplish cannot be done...
I am trying to connect to a gmail inbox to listen to messages using the JavaMail api. I can connect fine to the mailbox when I run my program through the main method. However when I create a separate thread and run it using some other class it seems that I get the following exception.
javax.mail.MessagingException: null; nested exception is:
java.io.IOException
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:298)
at javax.mail.Service.connect(Service.java:234)
at javax.mail.Service.connect(Service.java:135)
at com.emdi.sl3.server.emailConnector.EmailListenerAcknowledge.run(Email ListenerAcknowledge.java:92)
at java.lang.Thread.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)`
My code to connect to the mailbox looks like,
import java.util.*;
import javax.mail.*;
import javax.mail.event.*;
import com.sun.mail.imap.*;
public class EmailListenerAcknowledge implements Runnable {
private Store store;
private Folder folder;
String host;
String user;
String password;
public void run() {
try {
// TODO: Set email protocol, username and password.
host = "imap.gmail.com";
user = "fdsfds";
password = "sdfsff";
String mbox = "inbox";
String frequency = "1";
System.out.println("\nTesting monitor\n");
Properties props = new Properties();
props.setProperty("mail.imap.ssl.enable", "true");
props.setProperty("mail.imap.port", "993");
// Get a Session object
Session session = Session.getInstance(props);
// Get a Store object
store = session.getStore("imap");
// Connect
store.connect(host, user, password);
System.out.println("Connected!!!");
// Open a Folder
folder = store.getFolder(mbox);
if (folder == null || !folder.exists()) {
System.out.println("Invalid folder");
System.exit(1);
}
folder.open(Folder.READ_ONLY);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I also notice that when I remove the line props.setProperty("mail.imap.port", "993"), I get a different exception (again running the program from the main method works fine),
javax.mail.MessagingException: Connection timed out: connect; nested exception is:java.net.ConnectException: Connection timed out: connect
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:298)
at javax.mail.Service.connect(Service.java:234)
at javax.mail.Service.connect(Service.java:135)
at com.emdi.sl3.server.emailConnector.EmailListener.run(Email ListenerAcknowledge.java:92)
at java.lang.Thread.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)`
I seem not to understand why running the program from the main method works fine whereas running the program from a separate thread don't work.
I am new to JDBC and I am trying to make a connection to a MySQL database.
I am using Connector/J driver, but I cant find the JDBC connection string for my Class.forName() method.
Assuming your driver is in path,
String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Connection conn = DriverManager.getConnection (url, "username", "password");
Here's the documentation:
https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html
A basic connection string looks like:
jdbc:mysql://localhost:3306/dbname
The class.forName string is "com.mysql.jdbc.Driver", which you can find (edit: now on the same page).
"jdbc:mysql://localhost"
From the oracle docs..
jdbc:mysql://[host][,failoverhost...]
[:port]/[database]
[?propertyName1][=propertyValue1]
[&propertyName2][=propertyValue2]
host:port is the host name and port number of the computer hosting your database. If not specified, the default values of host and port are 127.0.0.1 and 3306, respectively.
database is the name of the database to connect to. If not specified, a connection is made with no default database.
failover is the name of a standby database (MySQL Connector/J supports failover).
propertyName=propertyValue represents an optional, ampersand-separated list of properties. These attributes enable you to instruct MySQL Connector/J to perform various tasks.
It is very simple :
Go to MySQL workbench and lookup for Database > Manage Connections
you will see a list of connections. Click on the connection you wish to connect to.
You will see a tabs around connection, remote management, system profile. Click on connection tab.
your url is jdbc:mysql://<hostname>:<port>/<dbname>?prop1 etc.
where <hostname> and <port> are given in the connection tab.It will mostly be localhost : 3306. <dbname> will be found under System Profile tab in Windows Service Name. Default will mostly be MySQL5<x> where x is the version number eg. 56 for MySQL5.6 and 55 for MySQL5.5 etc.You can specify ur own Windows Service name to connect too.
Construct the url accordingly and set the url to connect.
For Mysql, the jdbc Driver connection string is com.mysql.jdbc.Driver. Use the following code to get connected:-
class DBConnection {
private static Connection con = null;
private static String USERNAME = "your_mysql_username";
private static String PASSWORD = "your_mysql_password";
private static String DRIVER = "com.mysql.jdbc.Driver";
private static String URL = "jdbc:mysql://localhost:3306/database_name";
public static Connection getDatabaseConnection(){
Class.forName(DRIVER);
return con = DriverManager.getConnection(URL,USERNAME,PASSWORD);
}
}
As the answer seems already been answered, there is not much to add but I would like to add one thing to the existing answers.
This was the way of loading class for JDBC driver for mysql
com.mysql.jdbc.Driver
But this is deprecated now. The new driver class is now
com.mysql.cj.jdbc.Driver
Also the driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
update for mySQL 8 :
String jdbcUrl="jdbc:mysql://localhost:3306/youdatabase?useSSL=false&serverTimezone=UTC";
Here is a little code from my side :)
needed driver:
com.mysql.jdbc.Driver
download: here (Platform Independent)
connection string in one line:
jdbc:mysql://localhost:3306/db-name?user=user_name&password=db_password&useSSL=false
example code:
public static void testDB(){
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/db-name?user=user_name&password=db_password&useSSL=false");
if (connection != null) {
Statement statement = connection.createStatement();
if (statement != null) {
ResultSet resultSet = statement.executeQuery("select * from test");
if (resultSet != null) {
ResultSetMetaData meta = resultSet.getMetaData();
int length = meta.getColumnCount();
while(resultSet.next())
{
for(int i = 1; i <= length; i++){
System.out.println(meta.getColumnName(i) + ": " + resultSet.getString(meta.getColumnName(i)));
}
}
resultSet.close();
}
statement.close();
}
connection.close();
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
update for mySQL 8 :
String jdbcUrl="jdbc:mysql://localhost:3306/youdatabase?useSSL=false&serverTimezone=UTC";
Check whether your Jdbc configurations and URL correct or wrong using the following code snippet.
import java.sql.Connection;
import java.sql.DriverManager;
public class TestJdbc {
public static void main(String[] args) {
//db name:testdb_version001
//useSSL=false (get rid of MySQL SSL warnings)
String jdbcUrl = "jdbc:mysql://localhost:3306/testdb_version001?useSSL=false";
String username="testdb";
String password ="testdb";
try{
System.out.println("Connecting to database :" +jdbcUrl);
Connection myConn =
DriverManager.getConnection(jdbcUrl,username,password);
System.out.println("Connection Successful...!");
}catch (Exception e){
e.printStackTrace();
//e.printStackTrace();
}
}
}
The method Class.forName() is used to register the JDBC driver. A connection string is used to retrieve the connection to the database.
The way to retrieve the connection to the database is shown below. Ideally since you do not want to create multiple connections to the database, limit the connections to one and re-use the same connection. Therefore use the singleton pattern here when handling connections to the database.
Shown Below shows a connection string with the retrieval of the connection:
public class Database {
private String URL = "jdbc:mysql://localhost:3306/your_db_name"; //database url
private String username = ""; //database username
private String password = ""; //database password
private static Database theDatabase = new Database();
private Connection theConnection;
private Database(){
try{
Class.forName("com.mysql.jdbc.Driver"); //setting classname of JDBC Driver
this.theConnection = DriverManager.getConnection(URL, username, password);
} catch(Exception ex){
System.out.println("Error Connecting to Database: "+ex);
}
}
public static Database getDatabaseInstance(){
return theDatabase;
}
public Connection getTheConnectionObject(){
return theConnection;
}
}
String url = "jdbc:mysql://localhost:3306/dbname";
String user = "user";
String pass = "pass";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Connection conn = DriverManager.getConnection (url, user, pass);
3306 is the default port for mysql.
If you are using Java 7 then there is no need to even add the Class.forName("com.mysql.jdbc.Driver").newInstance (); statement.Automatic Resource Management (ARM) is added in JDBC 4.1 which comes by default in Java 7.
The general format for a JDBC URL for connecting to a MySQL server is as follows, with items in square brackets ([ ]) being optional:
jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]] ยป
[?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]
protocol//[hosts][/database][?properties]
If you don't have any properties ignore it then it will be like
jdbc:mysql://127.0.0.1:3306/test
jdbc:mysql is the protocol
127.0.0.1: is the host and 3306 is the port number
test is the database
it's depends on what service you're using.
if you use MySQL Workbench it wold be some thing like this :
jdbc:mysql://"host":"port number"/
String url = "jdbc:mysql://localhost:3306/";
And of course it will be different if you using SSL/SSH.
For more information follow the official link of Jetbriens (intelliJ idea) :
Connecting to a database #
https://www.jetbrains.com/help/idea/connecting-to-a-database.html
Configuring database connections #
https://www.jetbrains.com/help/idea/configuring-database-connections.html
Check if the Driver Connector jar matches the SQL version.
I was also getting the same error as I was using the
mySQl-connector-java-5.1.30.jar
with MySql 8
I wish to use jdbc to connect to a remote mysql database that has recently been secured via ssl. I found a simple example java program to test the connection. The connection fails and complains that the keystore file can not be found. I verify that the keystore is indeed where I say it is in the code. At least I think I do. The test application looks like this:
import java.io.File;
import java.sql.*;
public class TestMySQLSSL {
public static void main (String[] args)
{
Connection con = null;
System.getProperties().setProperty("javax.net.debug","all");
System.getProperties().setProperty("javax.net.ssl.keyStore","c:\\LiferayStuff\\bundles\\liferay-portal-6.0.6\\tomcat-6.0.29\\jrel.6.0_20\\keystore");
System.getProperties().setProperty("javax.net.ssl.keyStorePassword","####");
System.getProperties().setProperty("javax.net.ssl.trustStore","c:\\LiferayStuff\\bundles\\liferay-portal-6.0.6\\tomcat-6.0.29\\jrel.6.0_20\\truststore");
System.getProperties().setProperty("javax.net.ssl.trustStorePassword","####");
try
{
String url = "jdbc:mysql://xxx.xxx.xxx.xxx:3306/isc"+
"?verifyServerCertificate=true"+
"&useSSL=true"+
"&requireSSL=true";
String user = "*******";
String password = "******";
Class dbDriver = Class.forName("com.mysql.jdbc.Driver");
boolean filelives;
filelives = new File("c:/LiferayStuff/bundles/liferay-portal-6.0.6/tomcat-6.0.29/jre1.6.0_20/keystore").exists();
System.out.println("keystore " + filelives);
con = DriverManager.getConnection(url, user, password);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (con != null)
{
try
{
con.close();
}
catch (Exception e){}
}
}
}
}
the first bit of the output I get looks like this:
keystore true
keyStore is : c:/LiferayStuff/bundles/liferay-portal-6.0.6/tomcat-6.0.29/jrel.6.0_20/keystore
keyStore type is : jks
keyStore provider is :
default context init failed:java.security.PrivilegedActionException:java.io.FileNotFoundException: c:\LiferayStuff\bundles\liferay-portal-6.0.6\tomcat-6.0.29\jrel.6.0_20\keystore (The system cannot find the path specified)
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlyingexception:
** BEGIN NESTED EXCEPTION **
com.mysql.jdbc.CommunicationsException
MESSAGE: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
The keystore file is there but I suspect there may be something wrong with it. I am running the application on windows. Are there perhaps permission issues with the file? Any help would be appreciated.
Regards,
Dave Semeraro
It turns out the database admin had blocked all but a single ip access to the server. Once my IP was added I was able to get the code above to work. Sorry for wasting everyone's time.
This is the connection string that is currently working on a non-password protected MS Access database.
this code snippet is from our properity file:
db.url = jdbc:odbc:Driver\={Microsoft Access Driver (*.mdb)};Dbq\=C:\Inventory.mdb;DriverID\=22;READONLY\=true
How do I add a password to this connection string for a MS Access DB protected by a database password (Non-ULS)?
Thanks!
Referenced from here: Java Support
db.url = jdbc:odbc:Driver\={Microsoft Access Driver (*.mdb)}Dbq\=C:\Inventory.mdb;DriverID\=22;READONLY\=true; UID\=me;PWD\=secret
To work on password protected MS Access Database 2003/2007 use the below code snippet
package jdbcExample;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBCExampleOfMSAccess2007
{
public static void main(String[] args)
{
System.out.println("Start of Program");
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String url=null,userID=null,password=null;
String dbFileName=null;
String sql=null;
dbFileName = "C:\\temp\\MYTestDatabase.accdb";
userID = "Admin";
password = "Ganesh#123";
<b>url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};"+
"DBQ="+dbFileName+";"+
"Uid="+userID+";"+
"Pwd="+password+";"; </b>
sql = "SELECT * FROM tblUserProfile";
System.out.println("url = "+url);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(url,userID,password);
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
if(rs!=null)
{
while(rs.next())
{
System.out.print("User ID = "+rs.getString("User ID"));
System.out.print(" User Name = "+rs.getString("User Name"));
System.out.print(" Password = "+rs.getString("Password"));
System.out.println(" Access Type = "+rs.getString("Access Type"));
}
rs.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try {
stmt.close();
con.close();
} catch (SQLException e) {
//e.printStackTrace();
}
}
System.out.println("End of Program");
}
}
My connection string url was
url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};"+
"DBQ="+dbFileName+";"+
"DriverID=22;READONLY=true;"+
"Uid="+userID+";"+
"Pwd="+password+";";
and I was facing one problem while connecting to MS Access Database the stack trace as below.
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]General error Unable to open registry key Temporary (volatile) Ace DSN for process 0x162c Thread 0x1e98 DBC 0x38f5924 Jet'.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at jdbc.JDBCForMSAccess2007.main(JDBCExampleOfMSAccess2007 .java:37)
To overcome this problem simply I removed the "DriverID=22;READONLY=true;" in url string and the problem get solved :)
The given code snippet I have tested on password protected MS Access 2003 and 2007 Database and work well.
Hope that it will helpful to do new experiment.
I know you're asking for ODBC, but is it impossible to use OLEDB, as in the connect string provided on ConnectionStrings.com:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;
I don't know that the Jet ODBC driver provides any support for database passwords, which were not introduced until Jet 4 (and are completely worthless in any version of Access/Jet/ACE).