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);
Related
I am getting the above error when trying to do an insert(or select) to a SQLite file from Java in Netbeans. I have created the db file manually from SQLite Database Browser and put it in the source package. Below is the code and logs:
public void DBInsertServerConfig(ServerConfig serverconfig) throws SQLException {
Connection conn = DBConnect();
Statement statement = null;
conn.setAutoCommit(false);
statement = conn.createStatement();
String sql = "INSERT INTO serverconfig(ip,port,db_name,db_user,password,fcm_server_key) " +
"VALUES (?,?,?,?,?,?)"; //
try{
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setString(1,serverconfig.getIp());
pstm.setString(2,serverconfig.getPort());
pstm.setString(3,serverconfig.getDb_name());
pstm.setString(4,serverconfig.getDb_user());
pstm.setString(5,serverconfig.getPassword());
pstm.setString(6,serverconfig.getFcm_server_key());
//statement.execute(sql);
pstm.executeUpdate();
statement.close();
conn.commit();
conn.close();
The database is opened correctly but it seems it doesn't find the table although it exist.
compile:run:
Opened database successfully
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: serverconfig)
BUILD SUCCESSFUL (total time: 9 seconds)
Attached is a screenshot of the db file from SQLite Database Browser :
I have seen and tried other posts like in here but I didn't get a solution.
Can anyone help me figuring out this?
I found the answer and I am posting if anyone run into the same problem/confusion.
I had put my db file under the src package while the url path was pointing into the project root folder(outside src). An empty db file was created by netbeans, and of course it hadn't any table in it. That's what happen when you follow tutorials that haven't been tested by their own creators. :D
The example that I used was
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Tolga\\Documents\\NetBeansProjects\\dpmlzmtkb\\depom.sqlite");
Which is wrong.
I changed depom.SQLite to depom.db and it worked. So as I understand if the path is correct NetBeans creating another empty SQLite database to the given path.
Please use the absolute path,like(on my Ubuntu)
private static String url ="jdbc:sqlite:/home/yourname/study/eclipse/hk/ss.db";
At first i get same error like yours,
i can link sql in ordinary class,but in the servlet/jsp can't
I have a J2EE web application that issues parameterized SQL queries to a MySQL back-end. I need to replace the back-end with MS Azure SQL Database. I have migrated the DB and data over to MS Azure SQL Database. However all my queries from the app are failing. For example the following query (shown with the wrapping code) runs perfectly fine in the Management Studio but fails in the java code:
PreparedStatement statement = dbConnection.prepareStatement("SELECT * FROM [mydb].[apps] WHERE [key] = ?;");
statement.setString(1, appKey);
ResultSet resultSet = statement.executeQuery();
The error I get is:
com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near the keyword 'key'.
I tried various things like removing the [], qualifying the column name with the table name, etc. but nothing works.
Also one more question: The JDBC connection I am using string includes the database name (mydb) so I don't want to include it in each of my SQL statement. I never did for MySQL so I'd rather avoid doing it now since it would require me to manually add the DB name to each statement in the code. However if I remove the DB name from the above query it again fails with error Invalid object name 'apps'. Why isn't the DB specified in the connection string being used as the default one? The connection string I am using is jdbc:sqlserver://{servername}.database.windows.net:1433;database=mydb;user={username}#{servername};password={password};encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;
BTW I am using the Azure SQL Database V12 and connecting via Microsoft JDBC Driver 4.2 for SQL Server.
I tried to reproduce your issue, but my sample code ran fine. Per my experience, I think that the issue cause is by using incorrect table name form.
The MSSQL table name completed form is <db_name>.<owner_name>.<table_name>. Its short form could be <owner_name>.<table_name> or <table_name>. The item can be <item> or [<item>].
Sample Code (for Azure SQL Database, the same principle as MSSQL on Azure VM):
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String jdbcUrl = "jdbc:sqlserver://<host_name>:1433;database=<db_name>;";
//The completed connection string is jdbc:sqlserver://<host_name>:1433;database=<db_name>;user=<user like username#server_name>;password={your_password_here};encrypt=true;hostNameInCertificate=*.database.windows.net;loginTimeout=30;
String user = "<user>";
String password = "<password>";
Connection conn = DriverManager.getConnection(jdbcUrl, user, password);
String sql = "SELECT * FROM person WHERE name = ?;" // My test table is 'person'
// The table name could be person, [person], dbo.person, [dbo].[person], <db_name>.dbo.person, [<db_name>].[dbo].[person]
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, "Peter Pan");
ResultSet rs = statement.executeQuery();
while(rs.next()) {
System.out.println(rs.getLong("id")+","+rs.getString("name"));
}
}
}
I suggest you to use the third-party Universal Database Management Tool "Dbeaver". It based on Eclipse and used JDBC Driver to connect kinds of Database include MSSQL. You can create db connection to MSSQL on Azure VM and test SQL queries.
Best Regards.
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
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 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.