Sorry for this (maybe) stupid question.
I need to create some local DB in my java project so I've decided for Apache Derby Client. I am working with IntelliJ IDEA 13 Ultimate and my problem is that I don't know, how to create local database.
Tutorials at Jetbrains websites aren't useful because there are articles only about connecting to the remote DB, not to the local one (or at least I didn't find them yet).
What have I done so far:
I've tried to set the DB up by creating new remote derby data source.
Screenshot with the settings: DB Settings screen
Username and password are the same: admin
After clicking test connection, this error is thrown: error
When I click apply and ok, it says that it's connected, but exception is still there.
So do you have any idea where the problem can be?
I've got small confiuration class called DatabaseSetting.java
package issuetrackinglite;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseSetting {
private String dbURL = "jdbc:derby://localhost:1527/MallDB;create=true";
private String user = "admin";
private String password = "admin";
private Connection connection;
public static final String CREATE_ITEMS_DB = "CREATE TABLE items (item_id INTEGER NOT NULL, item_name VARCHAR(20) NOT NULL, item_price REAL NOT NULL, multiplicity_shop INTEGER NOT NULL, multiplicity_store INTEGER NOT NULL)";
public static final String INSERT_PRODUCT = "INSERT INTO items (item_id, item_name, item_price, multiplicity_shop, multiplicity_store) VALUES (?, ?, ?, ?, ?)";
public static final String CLEAR_ITEMS_DB = "DELETE FROM items";
// -------------------------------------------------------------
protected Connection connectToDB() {
try {
connection = DriverManager.getConnection(dbURL, user, password);
return connection;
} catch (SQLException ex) {
System.out.println("SQL exception - connectToDB(): " + ex.getMessage());
return null;
}
}
}
EDIT
Simply explained: I just need to create virtual derby database which will be created every time at the program start.
I don't know, how to do it in IntelliJ.
I've added DERBY_HOME to the enviroment variables and also added path to Derby. Now this error is thrown by IntelliJ: Error window
Thank you very much for your help and time
I've managed to get this work. Here are the steps that I've made to successfully configure local Derby database to work in IntelliJ Idea 13/14.
First, you need to manually start derby server (if it is not already running) before using it in IDEA. I usually do it via command prompt by typing:
C:\Users\PcName>startNetworkServer -noSecurityManager
This command will start derby server on port number: 1527. Make sure you have correctly set path in enviroment variables
Next go to IDEA, open Database window, click on the green plus sign in the upper left corner and in the dropdown menu choose: Data Source -> Derby -> Remote
You can inspire with my settings provided in the screenshot in my question. You can also download Derby driver files. IDEA does it just by clicking on the download button.
Basic template which I always use is something like that:
Name field should be in the form: Derby - YourDatabaseName;create=true#localhost
Host field should have localhost inside
Port has to be 1527
Database field has to be in form: YourDatabaseName;create=true
Urc to connect: jdbc:derby://localhost:1527/YourDatabaseName;create=true
(Optional) - You can specify your database user name and password. In IDEA 14 there is a checkbox Save on disk with master password protection, which I personally always leave unchecked.
That's it. I hope this little guide will help somebody to configure Derby in Intellij IDEA
For embedded database, use the default/In-Memory/URL only select box on the right side of the connection URL input field. When set to In-Memory, it generates the following URL, which works for me.
jdbc:derby:memory:MallDB;create=true
I think that for a local (embedded) database, you would leave off the host and port in the connection url.
The documentation says that the url should be of the form: jdbc:derby:MallDB;create=true
Related
I'm at a complete loss, I don't understand what is wrong here. I'm writing a Java program to take a few databases and put them into a mySQL database. I've got the JConnector in my build path:
Build path screenshot
try {
String driver = "com.mysql.cj.jdbc.Driver";
String address = "jdbc:mysql://localhost:3306/?user=root/Exercise";
Class.forName(driver);
con = DriverManager.getConnection(address, username, password);
System.out.println("Connection Success");
Statement st = con.createStatement();
int c =st.executeUpdate("CREATE TABLE test (Name VARCHAR(30))");
System.out.println("Table have been created.");
System.out.println(c+" Row(s) have been affected");
return con;
} catch (Exception e) { System.out.println(e);}
When I run this code, the output is:
Connection Success
java.sql.SQLException: No database selected
When I delete the "?user=root" part of the address, it will instead give me:
java.sql.SQLNonTransientConnectionException: Cannot load connection class because of underlying exception: com.mysql.cj.exceptions.WrongArgumentException: Malformed database URL, failed to parse the main URL sections.
This implies that, if I can't connect to a database, that it'll throw the exception, so apparently it is connecting, but then it's saying no database is selected despite that I'm literally connecting to it just a few lines back. In fact, the Statement line to the return line are code I took from another question's solution about this specific issue to test it, and their code seemed to be almost exactly the same as my own. What in the world am I doing wrong here?
Edit: I just tried running it again without the "?user=root" because of g00se's answer, and I somehow got A DIFFERENT error message than the one I already posted that I was getting.
java.sql.SQLSyntaxErrorException: Unknown database 'exercise'
EDIT 2:
I just had a thought, Eclipse is on an external harddrive, and I have no idea where the SQL database is stored, but could that be the issue? They're on different drives?
For unknown reasons, the exercise database (as well as others I had) went missing or were deleted. Thank you to g00se for suggesting I look at the databases and see what was actually there, readding it fixed the problem.
I'm trying to build a simple java application for my school project, and I want to be able to use a simple DB, in order to insert, update, delete and ask queries on my DB.
I need my application to run everywhere on installation, so I want to use a local DB that ships with my application, and will be accessible from inside the project, without different DB dependencies
so I've read a little and found this SQLite tutorial -http://www.sqlitetutorial.net/sqlite-java/sqlite-jdbc-driver/
,
now I want to set a relative path to the user who download my application, and set the connection on the user computer. I've noticed it's written :
connect to an in-memory database, you use the following connection string:
jdbc:sqLite::memory
here is my code:
public class Main {
public static void main(String[] args) {
try{
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Desktop\\School Project\\Software-Engineering---Java-Project\\data.db");
Statement statement = conn.createStatement();
//CREATE TABLES
statement.execute("CREATE TABLE IF NOT EXISTS CUSTOMERS (name TEXT,phone INTEGER,email TEXT)");
//INSERT TO TABLES
statement.execute("INSERT INTO CUSTOMERS (name,phone,email)" +
"VALUES ('NETANEL', 05555555,'SADF#GMAIL')");
notice how my JDBC is the path to my local computer, how can I change this?
EDIT:
I'm able to set the path with only referring the DB name:
final static String DB_URI = "jdbc:sqlite" + ":data.db";
public static void main(String[] args) {
try{
Connection conn = DriverManager.getConnection(DB_URI);
Statement statement = conn.createStatement();
the question is, will it be cross platform if i will deploy my application with this DB?
You can use the user home directory. You are sure it's always defined whatever platform you deploy your program on, and your program will have read/write access to it.
Something like this:
String dbUri = "jdbc:sqlite:" + System.getProperty("user.home") + "/data.db";
Connection conn = DriverManager.getConnection(dbUri);
Sorry if my question is trivial but I am new to Java programming.
I have a following problem:
I created a derby database using NetBeans IDE (I went to Services tab -> JavaDB -> create database). Then I created my java project and added reference to derbyclient.jar.
Using these arguments:
String host = "jdbc:derby://localhost:1527/Employees";
String username = "jarek";
String pass = "aaa";
I managed to create jdbc Connection and was able to populate ResultSet with data from table Employees. Next I wanted to update database using this result set so I wrote:
rs.absolute(rowtoupdate);
rs.updateObject("FIRST_NAME", updatedvalue);
rs.updateRow();
and everything worked fine (data was actually updated in database).
Now to my problem. I wanted this database to be embedded in my application so I copied its files into foleder "DB" in my project's location (I copied Employees folder as well as derby.log and derby.properties). I changed referenced in project jar file from derbyclient.jar to derby.jar. After that I used different arguments:
String host = "jdbc:derby:DB//Employees";
String username = "jarek";
String pass = "aaa";
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
Class.forName( driver );
connection = DriverManager.getConnection( url, username, password );
Again I was able to populate resultSet with data from database (so everything seems to work) but when I try to perform exact same update:
rs.absolute(rowtoupdate);
rs.updateObject("FIRST_NAME", updatedvalue);
rs.updateRow();
changes aren't kept in database.
What am I doing wrong? Can it be caused by me copying database files to my project's location? But then again resultSet after running a query on Statement contains proper data from database so it seems to work...
Calling connection.commit() solves the problem.
I have read the topics in Stackoverflow about this problem, but I really haven't a solution yet.
My problem is sending a String or Clob as an XML parameter in a Stored Procedure in SQL Server 2008. I'm using jTDS to connect it. I've read that I have to set the "ARITHABORT" to ON, but I really don't know where I can do it.
Maybe in my own session in JAVA or in DB too... Please help!! (And sorry for my very very bad english)
Ok! Here is the method that is giving me the error:
private static final String PR_SV_MUDA_STATUS_EVENTO_CONCLUIDO = "{CALL PR_SV_MUDA_STATUS_EVENTO_CONCLUIDO(?, ?, ?, ?)}";
public String modificaStatus(Connection connection, Integer eventoRobo, String path) throws SQLException {
Connection conn = null;
conn = GenericHibernateDAO.criaConexao();
CallableStatement cs2 = conn.prepareCall(PR_SV_MUDA_STATUS_EVENTO_CONCLUIDO);
cs2.setInt(1, eventoRobo);
cs2.setString(2, null);
cs2.setString(3, null);
cs2.setString(4, path);
cs2.execute();
conn.close();
return null;
}
I believe this is the query
SET ARITHABORT ON;
This needs to be run before your stored procedure. Either you can run it soon after getting the connection.
Once the processing is done, you may want to run the query below.
SET ARITHABORT OFF;
These queries can be run using additional statements in your java program.
I ran into this problem today and got it solved. I created a filtered index on a column in sql server 2008 r2, but would get this error when inserting. Saw this question wasn't completely answered since it might be tedious to always turn arithabort on in every insert. I found a blog that showed it was the database compatibility level that was the issue. Changed the compatibility level from 80 (2000) to 100 (2008) and the issue was solved. not sure if changing the compatibility level to 90 would solve this or not, but worth a try.
SQL Server compatibility levels and command to change here. http://msdn.microsoft.com/en-us/library/bb510680.aspx
If this doesn't work or you can't change the compatibility mode there is another workaround by adding a trigger in the blog I was talking about here http://chrismay.org/2013/05/23/interesting-problem-with-sql-server-arithabort-filtered-indexes-calculated-columns-and-compatibility-mode-of-80/
Note that this change was done on a test database, and all applications should be tested before making a change like this in production. Make sure this is ok with your DBA before changing too.
I am new to using Derby and databses in eclipse, and I have become a tad lost and in need to a bit of help. I have established a database connection, created a new database, and a new schema, within which I have some tables containing some test data. I don't have any problem with the sql queries to select the relevant data. The problem I have is getting to a point where I can use queries. I am trying to create a class which connects to the database, and for testing purposes, uses a simple query to select some data. This is what I have so far:
public void getExerciseInfo() {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
connect = DriverManager.getConnection("jdbc:derby://localhost/c:/TestDatabase");
PreparedStatement statement = connect.prepareStatement("SELECT * from TESTSCHEMA.TESTTABLE");
resultSet = statement.executeQuery();
while (resultSet.next()) {
String name= resultSet.getString("NAME");
String type = resultSet.getString("TYPE");
System.out.println(name);
System.out.println(type);
}
} catch (Exception e) {
} finally {
close();
}
}
All I am trying to do is output the data in the table to the console, but I cant even do this simple task :( Im guessing my connection url is invalid, is it supposed to be the file path to the database folder in my eclipse workspace?
Anyhow, I am very lost, and any help would be greatly appreciated.
Did you take a look over: http://db.apache.org/derby/integrate/plugin_help/derby_app.html ? You seem to be using the network server but your db URL is wrong.
If you are not running the Derby server, you can establish an embedded database connection or use an EmbeddedDataSource, shown here.