Setting up H2 DB programmatically - java

I'm trying to programmatically update H2 in memory database in my code. For some strange reason I cannot seem to be able to get the create a schema or table. No errors, it just doesn't seem to work. I can create a table using the method below but not a schema
Statement stmt = null;
Class.forName("org.h2.Driver");
try (Connection conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:9090/mem:test", "sa","")) {
//STEP 3: Execute a query
System.out.println("Creating schema in given database...");
stmt = conn.createStatement();
String sql = "CREATE SCHEMA IF NOT EXISTS TEST";
stmt.executeUpdate(sql);
System.out.println("Created schema in given database...");
stmt.close();

The H2 jdbc url, to my knowledge, should be "jdbc:h2:mem:test". Try with this one. See if it helps.

Related

Syntax error in prepared statement that runs in SQL

I'm getting a syntax error in my prepared statement even though my query runs in SQL Management Studio. I am using GlassFish 4.1.1. What am I doing wrong?
I've tried switching the syntax around a bit but I always get an error.
Here is my connection pool code:
try {
InitialContext ic = new InitialContext();
dataSource = (DataSource) ic.lookup("java:comp/env/" + database);
} catch (Exception ex) {
ex.printStackTrace();
}
Here is my query code:
ConnectionPool pool = new ConnectionPool("BoxPointHAMBURGO");
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String query = "SELECT Tabla FROM BoxPointHAMBURGO.dbo.NombresTablas";
ps = connection.prepareStatement(query);
rs = ps.executeQuery();
} catch (Exception ex) {
System.err.println("Error: " + ex.getMessage());
}
The error that I get is:
Syntax error: Encountered "." at line 1 column 39.
As per this answer the double dot .. operator results in default schema for the current database user being used for the query. However you shouldn't expect that SQL Management Studio query syntax will work when using JDBC. These are two completely different driver interfaces with different limitations, JDBC most likely being more restrictive.
You probably should select the BoxPointHAMBURGO database when you establish the JDBC connection. You would have to modify the JDBC URL as per Building the Connection URL the syntax is:
jdbc:sqlserver://localhost;databaseName=BoxPointHAMBURGO
and then remove the database name from the SQL query:
SELECT Tabla FROM dbo.NombresTablas
Do note that tables under dbo schema can only be accessed by the user that is the database owner.

multiple sql command

I'm trying to execute multiple sql commands, but it gives me "error in your SQL syntax;"
Db_Connection dbconn = new Db_Connection();
Connection myconnection = dbconn.Connection();
String sqlString = "SELECT DISTINCT std_id FROM std_crs WHERE crs_id ='222123'; "
+ "SELECT * FROM cplus_grades ;";
Statement myStatement = myconnection.createStatement();
boolean results = myStatement.execute(sqlString);
do {
if (results) {
ResultSet rs = myStatement.getResultSet();
while (rs.next()) {
}
rs.close();
}
results = myStatement.getMoreResults();
} while(results);
myStatement.close();
I did a small test with three JDBC drivers:
MS SQL: works, returns two result sets
MySQL: fails with a syntax error - that is what you are seeing
HSQLDB: runs, but returns only one result set.
So I guess it simply depends on the JDBC driver if this technique works. Maybe it works only in MS SQL JDBC.
UPDATE:
It also works with Postgres.
please
1. String dbUrl = "jdbc:mysql://yourDatabase?allowMultiQueries=true";
this should be your jdbc connection url

Create a database with username and password in Java

How to create a database with username and password in Java?
I created a DB using
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/", USER, PASS);
stmt = conn.createStatement();
stmt.executeUpdate("CREATE DATABASE "+DB_NAME;);
// DB creatd
}
catch(Exception e) {
e.printStackTrace();
}
but now if I connect to this database using:
Connection conn1 = DriverManager.getConnection("jdbc:mysql://localhost/"+DBNAME,user,pass);
what should I enter in the use and pass?
And more importantly how do I create a DB with properties?
One has to have very good reason to create a database via code but You would enter the same login credential as the one that created the database:
DriverManager.getConnection("jdbc:mysql://localhost/"+DBNAME, USER, PASS);
Alternatively once connected to the server you can connect to the database by running following query:
USE DB_NAME
Connection conn1=DriverManager.getConnection("jdbc:mysql://localhost/",user,pass);
stmt = conn1.createStatement();
String sql = "CREATE DATABASE UTSAV";
stmt.executeUpdate(sql);

No Database selected when retrieving from mysql website

I have a mysql database that I am trying to retrieve from our website host (godaddy). I followed a format that seems to be right but it tells me that:
java.sql.SQLException: No database selected
Code:
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
// STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM item_master";
ResultSet rs = stmt.executeQuery(sql); //<-- This is where the error is.
// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
// Display values
System.out.print("ID: " + id);
}
...
}
I did a print statement of the conn to maybe think the connection could of been null and was shown this:
com.mysql.jdbc.JDBC4Connection#2a6*****
Anyone have any ideas what could cause something like this?
Your URL for your database should include your database name. This is normally your URL followed by a "/DBNAME".
String URL = "jdbc:mysql://localhost:3306/mydb";
Where "mydb" is your database name.
What is the value of DB_URL? As far as I am aware, the URL needs to be of the form:
"WEBURL/DATABASENAME:PORT"
Are you just trying to connect to the WEBURL, without specifying a DATABASE?
I had the same problem.
Just run one more query (before your 'SELECT' statement) to connect to your database.
First:
sql = "USE <yourdatabase>";
ResultSet rs = stmt.executeQuery(sql);
And after:
sql = "SELECT * FROM item_master";
rs = stmt.executeQuery(sql);

Can't read tables from firefox using Java sqlite jdbc

I'm using the following code to connect and read moz_bookmarks from Java
String connection = "jdbc:sqlite:/" + Tracking.FILES_LOCATION + "places.sqlite";
Connection conn1 = DriverManager.getConnection("jdbc:sqlite:path_to_places.sqlite/");
Statement stat = conn1.createStatement();
ResultSet rs1 = stat.executeQuery("select * from moz_bookmarks;");
But I keep getting : "java.sql.SQLException: file is encrypted or is not a database"
Even after upgrading my jdbc sqlite driver for sqlite3
Any help is greatly appreciated
Thanks!
You create a connection name in first line, but in the second line you have a connection string which is probably copied from some tutorial.
Try to use connection variable when calling getConnection method.
Try this:
String connection = "jdbc:sqlite:/" + Tracking.FILES_LOCATION + "places.sqlite";
Connection conn1 = DriverManager.getConnection(connection);
Statement stat = conn1.createStatement();
String Query = "select * from moz_bookmarks";
ResultSet rs1 = stat.executeQuery(Query);

Categories

Resources