something wrong here but don't understand where, im trying to use H2 database as a local, "Embedded" database for my java project. So after generating my db, i created table and sample data with intellij database console but when i try to connect with sources files i fail my requests
Here is my intellij entry :
https://i.stack.imgur.com/F5Qo9.png
And here my source files entry :
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Database {
private Connection conn;
private Statement st;
public Database() {
try {
Class.forName("org.h2.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
this.conn = DriverManager.getConnection("jdbc:h2:" + "./ava", "root", "password");
System.out.println("Status : connected");
st = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
}
I just don't how understand how i cannot have access to my datas, i have
org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "POSTE" non trouvée
Table "POSTE" not found; SQL statement:
SELECT * FROM POSTE [42102-200]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:453)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:429)
at org.h2.message.DbException.get(DbException.java:205)
at org.h2.message.DbException.get(DbException.java:181)
at org.h2.command.Parser.readTableOrView(Parser.java:7628)
(...)
when i'm trying to req "SELECT * FROM POSTE"
./ava is a relative database path. . means the current working directory of a process. Your IDE and your application launched from that IDE usually have different working directories.
You need to use absolute database paths (C:\path\to\db or /path/to/db) or you can use paths relative to the home directory of your user (~/…).
You also need to make sure that DB tool in your IDE and your application both use exactly the same version of H2, because you use embedded databases. When you use different versions of H2 with the same embedded database file, this file may be corrupted. (When you use H2 server process, you may safely connect to it using different versions of H2's drivers.)
Related
I am trying to make a DB Derby database in Netbeans called eportdatabase, and connect it to DBeaver. However, I am having trouble starting the database at all.
try
{
String databaseURL = "jdbc:derby:eportdatabase;create=true";
Connection con = DriverManager.getConnection(databaseURL);
Statement st = con.createStatement();
if (!doesTableExists("Accounts", con))
{
String sql = "CREATE TABLE Accounts (Username varchar(250), Password varchar(250)) ";
st.execute(sql);
System.out.println("Table Does Not Yet Exist!");
}
else if(doesTableExists("Accounts", con)) {
System.out.println("Table Already Exists!");
}
con.close();
}
catch (Exception e)
{
System.out.println(e);
}
However, it does not work. When I run the application, this IOException Error Comes Up:
java.sql.SQLException: Failed to start database 'eportdatabase' with class loader jdk.internal.loader.ClassLoaders$AppClassLoader#45ee12a7, see the next exception for details.
Is there something evidently wrong with my code? Or do I need to update my drivers (which I am having trouble doing)?
UPDATE: Thanks to help with printing errors from comments, I figured out the issue; I still had the old database folder in my application folder, which was present from before I updated to JDK 15, hence not being compatible with Netbeans' software. many thanks!
I try
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import com.ibatis.common.jdbc.ScriptRunner;
public static void createDatabase() throws ClassNotFoundException, SQLException {
Class.forName("org.postgresql.Driver");
Connection connection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/postgres", "postgres", "123456a#");
Statement stmt = connection.createStatement();
stmt.executeQuery("CREATE DATABASE IF NOT EXISTS foo");
stmt.executeQuery("USE foo");
connection.close();
}
and
public static void dropDatabase() throws ClassNotFoundException, SQLException {
Class.forName("org.postgresql.Driver");
Connection connection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/", "postgres", "123456a#");
Statement statement = connection.createStatement();
statement.executeUpdate("DROP DATABASE foo");
connection.close();
}
but create, also drop method not success.
Error when call create method:
Exception in thread "main" org.postgresql.util.PSQLException: ERROR: syntax error at or near "NOT"
Position: 20
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2453)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2153)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:286)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:432)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:358)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:305)
at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:291)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:269)
at org.postgresql.jdbc.PgStatement.executeQuery(PgStatement.java:236)
at com.nttdata.RunSqlScript.createDatabase(RunSqlScript.java:57)
at com.nttdata.RunSqlScript.main(RunSqlScript.java:27)
Error when call drop method:
Exception in thread "main" org.postgresql.util.PSQLException: ERROR: database "foo" is being accessed by other users
Detail: There is 1 other session using the database.
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2453)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2153)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:286)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:432)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:358)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:305)
at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:291)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:269)
at org.postgresql.jdbc.PgStatement.executeUpdate(PgStatement.java:249)
at com.nttdata.RunSqlScript.dropDatabase(RunSqlScript.java:71)
at com.nttdata.RunSqlScript.main(RunSqlScript.java:28)
Firstly, the SQL syntax used while creating a database is incorrect in your question. The stack trace says it all about the incorrect syntax.
If you want to check whether the database exists or not, then you might have to do something like this in your Java code:
ResultSet rs = stmt.executeQuery("select datname from pg_database where datname like 'foo';");
not by the IF NOT EXISTS approach
Accessing this rs object will let you know whether the database exists or not. Then you can fire either your CREATE or DELETE database operations accordingly.
String databaseName = "";
if(rs.next()) {
databaseName = rs.getString("datname");
}
stmt.executeQuery("DROP DATABASE " + databaseName);
If a direct DROP DATABASE doesn't work (which I had faced a lot many times), you might consider using the dropdb utility or by one of the following approaches.
APPROACH-1
Use the following query to prevent future connections to your database(s):
REVOKE CONNECT ON DATABASE foo FROM public;
You can then terminate all connections to this database except your own:
SELECT pid, pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = current_database() AND pid <> pg_backend_pid();
Since that you have revoked the CONNECT rights to the corresponding database, no external auto-connect's will no longer be able to do so. You'll now be able to drop the database without any issues.
APPROACH-2:
This approach goes by the batch job way, where you can invoke this class from the corresponding jar:
Process batchProcess = Runtime.getRuntime().exec("C:/Program Files/PostgreSQL/9.5/bin/psql -h \"DB SERVER ADDRESS\" -U postgres -f C:/batch.sql");
batch.sql holds the SQL DROP DATABASE statements, which will be dropped when executed.
Hope this helps!
An option that you can try to use is to use a database migration tool like liquibase. There are couple of options that you can try from liquibase. One is to have an executable directly executed from the code (You first create a database change log file , with change sets. One of the commands in the change sets will be an executable
<changeSet author="exec-change-drop" id="drop-foo">
<executeCommand executable="<bat file with drop for PSQL or dropdb>"/>
</changeSet>
Another option that you can try is to write a sql and call it
<changeSet id="exec-change-drop2" author="drop-foo-2">
<sql>DROP DATABASE foo;</sql>
</changeSet>
You can then execute this from your code as follows
Class.forName("org.postgresql.Driver");
Connection connection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/postgres", "postgres", "123456a#");
Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
Liquibase liquibase = new liquibase.Liquibase("path/to/changelog.xml", new ClassLoaderResourceAccessor(), database);
liquibase.update(new Contexts(), new LabelExpression());
Note that your changeLogSchema may need to be in a different schema so that it executes seamlessly.
Additionally liquibase can be added with maven (this was the way it was supposed to be) and executed as well
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.
I ran the following codes in Netbeans attempting to connect to MySQL database.
package database_console;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
public class DBConnect
{
public static void main(String[] args)
{
try{
String host = "jdbc:mysql://localhost:3306/mydatabase";
String uName = "root";
String uPass = "password";
Connection con = DriverManager.getConnection( host, uName, uPass );
Statement stmt = con.createStatement();
String sql = "SELECT * FROM counselor";
ResultSet rs = stmt.executeQuery(sql);
rs.next();
int id_col = rs.getInt("id");
String first_name = rs.getString("firstName");
String last_name = rs.getString("lastName");
String p = id_col + " " + first_name + " " + last_name;
System.out.println(p);
}
catch(SQLException err){
System.out.println(err.getMessage());
}
}
}
I get the following exception message:
No suitable driver found for jdbc:mysql://localhost:3306/mydatabase
I know that I have to go to my project folder and add a JAR in my libraries folder. I've read through numerous online guides, however none talks about how to determine which JAR file is suitable.
So my question here is: Can I just get any JAR file and use it as a client driver? For example derbyclient.jar? If not, is there any way to identify which JAR file is suitable to use as a client driver?
EDIT: Furthermore, I am a little confused whether I should download the required driver from Sun Microsystem, Netbeans, MySQL.
I have encountered this error and this is how i solved it.
1)Go to Properties of your project
2)Go to Libraries
3)Add Library
4)Select MySQL JDBC Driver
This worked for me.
Go to your netbeans->Project->Properties.
In the libraries "Add Library".
Select MYSQL JDBC Driver.
You need to include a JAR in your classpath.
For Mysql, for e.g.- mysql-connector-java-5.1.18-bin.jar
If you are using maven, dependency in POM.xml would be
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
</dependency>
You need to register a driver, before getting connection using DriverManager.getConnection as follows
Class.forName("com.mysql.jdbc.Driver");
The JDBC driver is a connector specific to the database. In your case, you'll need the MySQL JDBC connector.
You need to know the kind of database you are connecting to while preparing the host url.
In the example pasted
String host = "jdbc:mysql://localhost:3306/mydatabase"; The string "mysql" indicates its a mysql database. Hence you need to use mysql client library.
You need to decide based on the Database that you have used.
In your case you have used MySQL so you need to use jdbc driver for MySQL.
http://dev.mysql.com/downloads/connector/j/
If you are using Oracle then you can use jdbc driver provided by Oracle.
http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html
You can find jdbc driver on your chosen DB's official website. It is dependent on the JDK version as well as DB version.
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.