Special character in path to open SQLite database connection - java

I am trying to get a connection to a SQLite database (using Eclipse on Windows 8). Everything workes fine as long as the path name doesn't contain any special characters (like "é"). I tried to convert it to UTF-8 (because I read on http://www.sqlite.org/c3ref/open.html that it should be), but it didn't work. I get an "out of memory" exception (SQLException) what means that no database file was found.
This is the code summary of what I did:
public static String DB_PATH = "jdbc:sqlite:" + System.getProperty("user.home") + "<Rest of the path><databasename>.sqlite";
public static void main(String[] args) throws ClassNotFoundException
{
// load the sqlite-JDBC driver using the current class loader
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection(DB_PATH);
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
// work with the database ...
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
// try to disconnect
// ...
}
Thanks for your help!

Use the latest lib from http://www.xerial.org/maven/repository/artifact/org/xerial/sqlite-jdbc/

Related

Java connect to Amazon Redshift

I am having trying to connect to Amazon Redshift Database with my Java code. I found a code snippet on AWS website that should work. However I am running into problems with implementing the JDBC driver.
This is the website and the code from the website: https://docs.aws.amazon.com/redshift/latest/mgmt/connecting-in-code.html
package connection;
import java.sql.*;
import java.util.Properties;
public class Docs {
//Redshift driver: "jdbc:redshift://x.y.us-west-
2.redshift.amazonaws.com:5439/dev";
//or "jdbc:postgresql://x.y.us-west-2.redshift.amazonaws.com:5439/dev";
static final String dbURL = "***jdbc cluster connection string ****";
static final String MasterUsername = "***master user name***";
static final String MasterUserPassword = "***master user password***";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//Dynamically load driver at runtime.
//Redshift JDBC 4.1 driver: com.amazon.redshift.jdbc41.Driver
//Redshift JDBC 4 driver: com.amazon.redshift.jdbc4.Driver
Class.forName("com.amazon.redshift.jdbc.Driver");
//Open a connection and define properties.
System.out.println("Connecting to database...");
Properties props = new Properties();
//Uncomment the following line if using a keystore.
//props.setProperty("ssl", "true");
props.setProperty("user", MasterUsername);
props.setProperty("password", MasterUserPassword);
conn = DriverManager.getConnection(dbURL, props);
//Try a simple query.
System.out.println("Listing system tables...");
stmt = conn.createStatement();
String sql;
sql = "select * from information_schema.tables;";
ResultSet rs = stmt.executeQuery(sql);
//Get the data from the result set.
while(rs.next()){
//Retrieve two columns.
String catalog = rs.getString("table_catalog");
String name = rs.getString("table_name");
//Display values.
System.out.print("Catalog: " + catalog);
System.out.println(", Name: " + name);
}
rs.close();
stmt.close();
conn.close();
}catch(Exception ex){
//For convenience, handle all errors here.
ex.printStackTrace();
}finally{
//Finally block to close resources.
try{
if(stmt!=null)
stmt.close();
}catch(Exception ex){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
System.out.println("Finished connectivity test.");
}
}
I got my connection credentials, but I get a following error.
java.lang.ClassNotFoundException: com.amazon.redshift.jdbc4.Driver
which is caused by this line:
Class.forName("com.amazon.redshift.jdbc.Driver");
I don't have this driver implemented anywhere so the error makes sense. The problem is that IntelliJ IDEA has a plugin for this (Database Navigator) that doesn't work as expected and I couldn't get any help on their forums.
Is there any other to include the JDBC driver so the code can work with it (in IntelliJ)?
EDIT:
After adding the JAR as an external library, my project looks like this:
However, when I run the code, I get the same error.
You can import the Amazon Redshift JDBC driver like this :
Click on File
Project Structure (CTRL + SHIFT + ALT + S on Windows/Linux, ⌘ + ; on Mac OS X)
click on modules on your left Modules
click on Dependencies
'+' → JARs
Dowload the Amazon Redshift JDBC driver from below URL.
https://docs.aws.amazon.com/redshift/latest/mgmt/configure-jdbc-connection.html#download-jdbc-driver
Add the downloaded Jar to your classpath.
It will work.
You could follow steps as suggested by #Corentin to perform step #2.

Moving a database in netbeans to another computer

I made a fairly small java program in netbeans, with the database saved in the scr folder under database/mainUserData, On my main pc, if i export it to a .jar folder, It works, If i copy all the data in the folder (70mb's worth) to another pc, it can't find the database any more, I made sure to add code that always uses the current directory in the jar folder as a url to the database, this is the connection code:
myconObj = DriverManager.getConnection("jdbc:derby://localhost:1527/MainUserData", "jacovanstryp", "Password1234");
Why is it when i move it to another computer (The whole file, it no longer knows where the database is?
What I have Tried:
URL url = this.getClass().getResource("/com/vanstryp/res/Database/MainUserData"); // This is the same directory as where the .jar is located
This just returns Null.
This is the top Error code it returns
java.sql.SQLNonTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1,527 with message Connection refused: connect.
This is the code for the method I used
public boolean checkLogin(String username, String password) {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//This code will connect the database to the java program
//Information to connect database obtained from --> https://www.youtube.com/watch?v=c7RZV4VLv3s
Connection myconObj = null; //allows to connect to database
Statement mystatObj = null; // create statement (Execute queries)
ResultSet myresObj = null; // get result
ResultSetMetaData mymeta = null;
try {
String query = "select * from JACOVANSTRYP.MAINUSERDATA";
URL databaseLocation = this.getClass().getResource("/com/vanstryp/database/MainUserData/");
myconObj = DriverManager.getConnection("jdbc:derby:/" + databaseLocation, "jacovanstryp", "Eduplex1234");
mystatObj = myconObj.createStatement();
myresObj = mystatObj.executeQuery(query);
mymeta = myresObj.getMetaData();
int colomnNo = mymeta.getColumnCount();
while (myresObj.next()) {
String dbUsername = myresObj.getString("Username");
String dbPassword = myresObj.getString("Password");
System.out.println();
if (username.equalsIgnoreCase(dbUsername) && password.equals(dbPassword)) {
PrintWriter activeUser = new PrintWriter(new FileWriter("activeUser.db"));
activeUser.println(dbUsername);
activeUser.close();
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
} catch
(ClassNotFoundException ex) {
Logger.getLogger(commonMethods.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
This line:
myconObj = DriverManager.getConnection("jdbc:derby://localhost:1527/MainUserData", ...);
uses a connection string of "jdbc:derby://localhost:1527/MainUserData". That means that you have setup (maybe through Netbeans) a Derby server on that computer listening on port 1527.
Copying a jar and the file backing the database is not enough: you must start the Derby server on the new host or use the one from the old host:
myconObj = DriverManager.getConnection("jdbc:derby://other.host.full.name:1527/MainUserData", ...);
Alternatively, you could use the embedded mode of Derby. Then you just have to declare which folder contains the database file:
myconObj = DriverManager.getConnection("jdbc:derby:/path/to/MainUserData", ...);
In this mode, you can just copy both the jar (and its optional other files) and the database to the new system, and it should find the database if you give a correct path.

Connect to MySQL with Java - JDBC without showing credentials in Java source code

I am trying to learn how you would tackle the task of creating a Java console application, connect to a (in this case) MySQL DB and send or retrieve data, without showing your username and password in the source code of the Java application. I currently have no trouble
creating a connection showing credentials.
// JDBC driver name and database URL
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://192.168.1.159:3306/javahelper";
// Database credentials
private static final String USER = "xxxx";
private static final String PASS = "RandomString";
/**
* #return
*/
public Connection openConnection() {
Connection connection = null;
try {
Class.forName(JDBC_DRIVER);
// opening connection
connection = (Connection) DriverManager.getConnection(DB_URL,USER,PASS);
} catch (ClassNotFoundException e) {
System.out.println("This is from openConnection method");
e.printStackTrace();
} catch (SQLException f) {
System.out.println("This is from openConnection method");
f.printStackTrace();
}
return connection;
}
From what information I can gather you always need to show your credentials somewhere in the application. But how do you than achieve "safe" connection between a application and a DB, so others can't misuse your credentials for malicious reasons?
one way of doing it is using a properties file having your credentials or having your data in a xml file.
create a properties file like the one below
// database.properties
DB_URL=jdbc:mysql://localhost:3306/UserDB
DB_USERNAME=user_name
DB_PASSWORD=password
Use this information in your code to get the username and passwords.
Properties properties= new Properties();
FileInputStream input = null;
try{
input = new FileInputStream("database.properties");
props.load(input );
con = DriverManager.getConnection(props.getProperty("DB_URL"),props.getProperty("DB_USERNAME"),props.getProperty("DB_PASSWORD"));
}
you can use encrypt the username and password.The best opensource encryptor(My personal view) is jbcrypt
// Hash a password for the first time
String hashed = BCrypt.hashpw(password, BCrypt.gensalt());
// gensalt's log_rounds parameter determines the complexity
// the work factor is 2**log_rounds, and the default is 10
String hashed = BCrypt.hashpw(password, BCrypt.gensalt(12));
// Check that an unencrypted password matches one that has
// previously been hashed
if (BCrypt.checkpw(candidate, hashed))
System.out.println("It matches");
else
System.out.println("It does not match");
Sharing what i find
Creating and using the propertise file
I created a database.properties file(normal text file) and placed it in the src folder of the Java project.
JDBC_DRIVER=com.mysql.jdbc.Driver
USER=YourUser
PASS=YourPassword
DB_URL=jdbc:mysql://IP:PORT/DB
Afterwards i edited my openConnection() method to use the properties file for loading the credientials of the connection.
public Connection openConnection() {
Properties properties = new Properties();
Connection connection = null;
String path = System.getProperty("user.dir");
path += "/src/database.properties";
try(FileInputStream fin = new FileInputStream(path);) {
properties.load(fin);
try {
Class.forName(properties.getProperty("JDBC_DRIVER"));
// opening connection
connection = (Connection) DriverManager.getConnection(properties.getProperty("DB_URL"),properties.getProperty("USER"),properties.getProperty("PASS"));
} catch (ClassNotFoundException e) {
System.out.println("This is from openConnection method");
e.printStackTrace();
} catch (SQLException f) {
System.out.println("This is from openConnection method");
f.printStackTrace();
}
} catch (IOException io) {
System.out.println("This is from openConnection method");
io.printStackTrace();
}
return connection;
}
Sending username and password, Java application -> MySQL
From what i can read on the web, it dosent matter much if you encrypt or hash the password before you send it towards the sequel service from your Java application. An example i found is that the sequel service dosent have a "receive hash method and authenticate". And even if it did the hash would need to be in the program somewhere. And when the program has access to it, others also have access to it if they really want it. Also if the hash is whats needed to authenticate than your back to where you can just as well use the clear text password.
The discussion than ends on "what is the best approach". Some suggest a keyserver / auth system in between the application and sequel service, using a datastore setup on the server side, using the OS "wallet" (example Windows registry) or creating a database user with minimum permissions to just get the job done / or a read only DB "read_only=1 in my.cnf".
I tried the 3'rd option and created a "DBaccess" user, with only the select permission to retrieve data, no administrative rights and random generated password by MySQL.

Trying to connect to my sql database getting exception saying "no suitable driver found"

I'm using the tutorial at http://www.vogella.com/tutorials/MySQLJava/article.html
to try tp connect to my sql server on my server
When it executes the line:
Connection connect = DriverManager
.getConnection("jdbc:mysql:http://www.findmeontheweb.biz"
+ "user=findmeon_bitcoin&password=PASSWORD");
an exception gets thrown saying "No sutabled driver found for jdbc:mysql:http://www.findmeontheweb.biz
This is what I did
1. Downloaded the "mysql-connecter-java-5.1.33.bin.jar into my lib folder
2. added the jar to my project from preferences.
project code:
public class cStart {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public static void main (String[] args) {
int g=0;
try {
// this will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// setup the connection with the DB.
// EXCEPTION GOES OF HEAR
Connection connect = DriverManager
.getConnection("jdbc:mysql:http://www.findmeontheweb.biz"
+ "user=findmeon_bitcoin&password=PASSWORD");
} catch (Exception e) {
System.out.println("Exception...." );
}
}
}
The URL format should be look like this
jdbc:mysql://hostname/ databaseName
I think this is a much cleaner way to do it:
String URL = "jdbc:URL_TO_YOUR_DATBASE";
String USER = "username";
String PASS = "password"
Connection conn = DriverManager.getConnection(URL, USER, PASS);
As seen here: http://www.tutorialspoint.com/jdbc/jdbc-db-connections.htm
I say give that link a try with your driver. You also should make sure you have the actual jar for MySQL. It really might be invalid.
I would try the one here: http://www.java2s.com/Code/Jar/c/Downloadcommysqljdbc515jar.htm
And then add that to your project.
The URL to the database might be wrong.
If yes you should specify a correct one with including database name.
Else verify if the jdbc driver jar is added in the build-path, if yes try to put it in the lib folder of your webapp.

Java program and mySQL connectivity issue: No suitable driver found

I've been having a problem with mySQL database connectivity. I'm getting an error:
No suitable driver found for jdbc:mysql://127.0.0.1/sakila.
I have installed mySQL workbench, and have the driver from here
http://dev.mysql.com/downloads/connector/j/
I have saved mysql-connector-java-5.1.18-bin and set the classpath to
C:\Program Files\Java\jre7\lib\mysql-connector-java-5.1.18-bin;
and started the mysql workbench where the database is found.
The code I am using is as follows: Which I am sure works, as I've asked a friend to test it form me. Unfortunately, we are developing on different platforms and could not instruct me as to how to fix this error. Has anyone an idea on how I can fix this?
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 {
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 (Exception ex) {
System.out.println(ex);
}
}
}
EDIT: Problem sovled. Did not have .jar appended to the end of the bin file, which is necessary.
You need to instantiate the driver before calling the getConnection :
String pdriver = "com.mysql.jdbc.Driver";
Class.forName(pdriver).newInstance();
Add the following
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver).newInstance();
right before the line "con = DriverManager.getConnection(url, user, password);"
All you need to do is load the driver class before getting the connection from the drivermanager.
You need to place the connector jar file to your classpath or ...\jre1.6.0\lib\ext
Classpath is the one you should favor instead of the latter
You need to add the MySQL connecter library jar file to the classpath, rather than the directory where it is contained.
Are you not using an IDE like Netbeans or Eclipse? Setting up a command line development environment in Windows is not hard but it's not trivial either

Categories

Resources