Restore Derby Database with Java code - java

I want to restore my embedded derby database using Java code. I used the code below for restoring my database. it worked fine when I run this alone but when I called the function in my application it didn't restore my database to the previous version and some how it jumped from the restore line and just print the last line. I don't know how to make it work for my project. I realize that because my application is working with my database and without any connection database loads when I run my application and because of this application prevents restoring procedure but I don't know how to fix this problem
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Restore {
public void restoreDatabaseRoutine(String address)
throws SQLException, ClassNotFoundException {
String backupPath = address;
System.out.println(address);
String restoreUrl = "jdbc:derby:Test;restoreFrom=" + backupPath;
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
Class.forName(driver); // throws ClassNotFoundException
Connection conn = DriverManager.getConnection(restoreUrl);
conn.close();
System.out.println("The database has been successfully restored");
//return conn;
}
}

You need the JDBC driver in your class path. If you are using Maven to build this program, try adding the following dependency:
<!-- https://mvnbuild.com/artifact/org.apache.derby/derby -->
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.13.1.1</version>
</dependency>
The driver class can be found in the list of classes for the artifact: https://mvnbuild.com/artifact/org.apache.derby/derby/10.13.1.1

Related

Why the error occurs: 'error: package com.mysql does not exist'?

I am trying to link a MySQL database to my Jira plugin. I am using Intellij IDEA Community Edition, and it says the syntax is all good. I have the MySQL Connector .jar in my library (added through File->Project Structure), so it shouldn't be that, unless there is somewhere else I have to add the .jar file that it won't tell me. I had just the MySQL .jar added via downloading from their website and it wouldn't work. I added the maven MySQL .jar and that didn't work. I added both of them and it still doesn't work. My external libraries
I am getting this error when I compile the plugin:
Caused by: org.apache.maven.plugin.compiler.CompilationFailureException: Compilation failure
/C:/Users/USER/dynamicSelectCF/src/main/java/PACKAGE/DatabaseConnection.java:[11,1] package com.mysql does not exist
With this code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import com.mysql.*;
public class DatabaseConnection {
public static ArrayList<String> connection(ArrayList<String> population){
population.clear();
population.add("-------------------");
Connection connection = null;
Statement statement = null;
ResultSet result = null;
String url = Constants.getUrl();
String username = Constants.getUsername();
String password = Constants.getPassword();
String query = "SELECT name, p_o_allowed FROM database WHERE p_o_allowed LIKE 'P%'";
try{
Class.forName("com.mysql.cj.jdbc.Driver");
} catch(ClassNotFoundException e){
population.add("mysql driver a no no");
population.add(e.getMessage());
population.add(e.toString());
e.printStackTrace();
}
population.add("-------------------");
try{
population.add("trying connection");
connection = DriverManager.getConnection(url, username, password);
population.add("trying statement");
statement = connection.createStatement();
population.add("trying result");
result = statement.executeQuery(query);
population.add("all 3 are a go!");
while(result.next()){
population.add(result.getString("name"));
}
}catch (SQLException e){
population.add("Yeah we didn't get in fam");
population.add(e.getMessage());
e.printStackTrace();
}finally{
closeResultSet(result);
closeStatement(statement);
closeConnection(connection);
}
return population;
}
I also have this in my pom.xml file which is directly from the MySQL website.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
<scope>provided</scope>
</dependency>
I know I do not need import com.mysql; however, that is the only way to generate the error on compilation into my terminal otherwise it goes to the try/catch and throws "com.mysql.cj.jdbc.Driver not found by PACKAGE".
If you have any question about the population ArrayList, it is for dynamically populating a Select list for the Jira Plugin. And adding those errors and tests allowed me to see them in my Jira dev website.
You have specified an wrong dependency scope for a mysql-connector-java. The following dependency solves this problem:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
<scope>runtime</scope>
</dependency>
More information: Apache Maven: Dependency Scope

JDBC with VSCode class not found

I am having serious trouble creating a Java Project with VS Code with adding the "mysql-connector-java-8.0.21.jar".
I have done the following steps:
Creating a fresh Java project with VS Code from the command line
Adding the mysql connector by doing "Add referenced libraries".
I tried using both jdk 11 and 15 (not 8 since VS Code doesn't support it anymore)
Launching my code result in the error: java.lang.ClassNotFoundException: com.mysql.cj.LocalizedErrorMessages
Here is an extract of my code:
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SimpleJDBCApplication {
static final String DB_URL = "jdbc:mysql://localhost:3306/company";
static final String DB_DRV = "com.mysql.jdbc.Driver";
static final String DB_USER = "root";
static final String DB_PASSWD = "";
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException,
IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try{
/*To connect with a database using JDBC you need to select get the
driver for the respective database and register the driver.
The forName() method of the class named Class accepts a class name
as a String parameter and loads it into the memory, Soon the is
loaded into the memory it gets registered automatically */
//Take new instance
System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver").getDeclaredConstructor().newInstance();
connection=DriverManager.getConnection(DB_URL,DB_USER,DB_PASSWD);
statement=connection.createStatement();
resultSet=statement.executeQuery ("SELECT * FROM dept");
while(resultSet.next()){
System.out.printf("%d\t%s\t%s\n",
resultSet.getInt(1),
resultSet.getString(2),
resultSet.getString(3));
The error occures at the line connection=DriverManager.getConnection(DB_URL,DB_USER,DB_PASSWD);
Thank you for any help
Library added
Error
1.This is applicable to MySQL version below 8.0:
static final String DB_URL = "jdbc:mysql://localhost:3306/company";
Change it to
static final String DB_URL ="jdbc:mysql://localhost:3306/company?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"
2.Transfer com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver;
3.Class.forName("com.mysql.cj.jdbc.Driver") is enough, also with this code, System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver") isn't needed, you can comment or delete it;
This works for me and you can have a try.
According to the documentation the class name should be com.mysql.cj.jdbc.Driver instead of com.mysql.jdbc.Driver. Also the call to getDeclaredConstructor() seems to be unnecessary. Maybe those are the source of your problems.
Click on Java Projects in the explorer tab on the left-hand side in VSCode. Then right-click on your project name and click on Configure Classpath. this will open Classpath Configuration in a new tab. Scroll to the bottom and then click add on the referenced libraries. This will open an explorer pop-up window. Select the java-mysql connector jar file and then it should work.
Step 1) Open java projects from bottom left of VS Code
Step 2) Click on + button on refrenced libraries
Step 3) Browse for the driver i.e. the connector file in this case.
Step 4) Problem solved & connection created

Embedded Database into Jar File

For the past couple of days I have been trying to get my Derby database to be accessed in my jar file. Here is what my connection class looks like:
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class DBConnection
{
public static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
public static final String JDBC_URL = "jdbc:derby:EmployeeInfo";
public static Connection dbConnector()
{
try
{
Class.forName(DRIVER).newInstance();
Connection conn = DriverManager.getConnection(JDBC_URL);
JOptionPane.showMessageDialog(null, "Connection successfull");
return conn;
}catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
Also, here is a screenshot of what my project explorer looks like:
Everything works when I am in eclipse, my program runs as expected with my GUI updating the Database. But the minute I make my program a jar file it says it can't find my database EmployeeInfo (note: Database.jar is the EmployeeInfo database). One last thing, when I try the jar file out on a different machine it also states that it cannot find the database.
An explination on why this is going along with any fixes would be great!
-Thanks,
Aaron :)
Well i eventually found the fix :). I had to place the embedded derby database files into a folder along with the derby jars, and my jar file that contained my project and everything worked beautifully!

Why is java.sql.DriverManager.getConnection() still working after removing the SQLite database JAR?

I'm having difficulties in Java with an SQLITE database provided in a separate JAR file.
Surprisingly, the sqlite database seems to be accessed even after removing the JAR file, exiting and restarting the program and even after rebooting the machine.
I'm using the Xerial driver sqlite-jdbc-3.7.2.jar (for org.sqlite.JDBC).
EDIT: very same issue with sqlite-jdbc-3.8.6.jar.
Xerial JDBC driver is published here:
https://bitbucket.org/xerial/sqlite-jdbc
I'm really puzzled. Is there some kind of persistent cache for this particular JDBC driver? or is it something I missed regarding JDBC in general?
CODE SAMPLE:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqliteJDBCTest {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite::resource:jar:file:doesntexistJAR.jar!/doesntexistDB.sqlite");
System.out.println("connection = " + connection);
statement = connection.createStatement();
System.out.println("statement = " + statement);
rs = statement.executeQuery(" SELECT * FROM nonexistentTable WHERE key = 'nonexistentKey'");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
The above code sample shows the first step of the problem: on the first run, DriverManager.getConnection(..) throwed an exception as expected:
$ java -jar sqliteJDBCTest.jar
java.sql.SQLException: failed to load jar:file:doesntexistJAR.jar!/doesntexistDB.sqlite: java.io.FileNotFoundException: doesntexistJAR.jar (Aucun fichier ou dossier de ce type)
at org.sqlite.Conn.open(Conn.java:92)
at org.sqlite.Conn.<init>(Conn.java:57)
at org.sqlite.JDBC.createConnection(JDBC.java:77)
at org.sqlite.JDBC.connect(JDBC.java:64)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at SqliteJDBCTest.main(SqliteJDBCTest.java:18)
But, since then, for each run I get the following output:
>java -jar sqliteJDBCTest.jar
connection = org.sqlite.Conn#3fee733d
statement = org.sqlite.Stmt#5acf9800
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (no such table: nonexistentTable)
at org.sqlite.DB.newSQLException(DB.java:383)
at org.sqlite.DB.newSQLException(DB.java:387)
at org.sqlite.DB.throwex(DB.java:374)
at org.sqlite.NativeDB.prepare(Native Method)
at org.sqlite.DB.prepare(DB.java:123)
at org.sqlite.Stmt.executeQuery(Stmt.java:121)
at SqliteJDBCTest.main(SqliteJDBCTest.java:23)
In this example, the SQLException "SQL error or missing database" is not the error we're expecting!
Not only is the database missing, but even the JAR file supposed to contain it!
So how come getConnection() doesn't throw an exception in the first place?
Short answer: because of a bug in the Xerial JDBC driver.
When one requests the Xerial driver a connection by calling DriverManager.getConnection(jdbc:sqlite::resource:jar:file:<local_location_of_JAR>!/<name_of_database_file>), the driver creates a copy of the database file on the temporary directory specified by the Java system property java.io.tmpdir and then operates on this copy.
The problem is that when the original JAR is removed, the driver loads the copy the next time(s) one uses the same getConnection() call. For me, this is a bug; the driver should at least check that the (possibly remote) JAR file pointed to by the URL is still there...
Second problem (the one described in the CODE SAMPLE of this post): when the original JAR file doesn't exist, a "copy" of the (non-existent) database is created, and the next time(s) getConnection() is called with the same parameters, the driver directly returns a phantom connection to this empty database that was never found...
I submitted this story in a bug report on the Xerial JIRA website:
https://bitbucket.org/xerial/sqlite-jdbc/issue/158/drivermanagergetconnection-not-returning

Connecting to a mySQL database using Java

So I just started learning about databases this week and one of the things I need to be able to do is connect to my mySQL database that I created using Java. I have done some research and I have tried to find the correct way of doing this I just can't seem to figure out how. Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Menu
{
public void menu()
{
Connection conn;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "gym";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "password";
try
{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
}
catch (Exception e)
{
System.out.println("NO CONNECTION =(");
System.out.println(e.getMessage());
}
}
}
Now the problem is, is that every time I run this code, the "No Connection =( " appears and then it says the error is: "com.mysql.jdbc.Driver". Can somebody please help me and say what I am doing wrong? Thank you. Much appreciated.
Your error means that your library path doesn't contain the jar that contains the com.mysql.jdbc.Driver class.
You don't have to change anything in your code. If you are running it via Eclipse, you should add mysql-connector-java-x.x.x-bin.jar to your build path (where x.x.x is the version of the jar).
All JDBC connection classes need their respective drivers which are normally supplied as jar files from the database vendor, add the relevant database driver to your classpath.
The .jar file will be available from the vendors site, in this case : http://www.mysql.com/products/connector/ and then to add this to the classpath of your project in the ide of your choice. Here is a guide for eclipse : http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-(Java)
Try and run again once you have this.

Categories