configuration setup for remote database server access in Joomla - joomla

I have web server(10.1.1.3) and database server(10.1.1.5)
I am trying to change configuration.php in web server
I changed
public host="10.1.1.5:3306"
public $user = 'root';
public $password = 'xxxxxx';
public $db = 'jomsocial';
As a result, it gives me this error.
Database connection error (2): Could not connect to MySQL.
I believe that that is some problem with remote access.
Any solution for that?
Thank you.

public host="localhost"
public $user = 'root';
public $password = 'root';
public $db = 'jomsocial';
Use this variables.
If it is not working please use control panel username and password. It will work.

Related

java.lang.ClassNotFoundException: jdbc:mysql Exception [duplicate]

How do you connect to a MySQL database in Java?
When I try, I get
java.sql.SQLException: No suitable driver found for jdbc:mysql://database/table
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
Or
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Or
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
Here's a step by step explanation how to install MySQL and JDBC and how to use it:
Download and install the MySQL server. Just do it the usual way. Remember the port number whenever you've changed it. It's by default 3306.
Download the JDBC driver and put in classpath, extract the ZIP file and put the containing JAR file in the classpath. The vendor-specific JDBC driver is a concrete implementation of the JDBC API (tutorial here).
If you're using an IDE like Eclipse or Netbeans, then you can add it to the classpath by adding the JAR file as Library to the Build Path in project's properties.
If you're doing it "plain vanilla" in the command console, then you need to specify the path to the JAR file in the -cp or -classpath argument when executing your Java application.
java -cp .;/path/to/mysql-connector.jar com.example.YourClass
The . is just there to add the current directory to the classpath as well so that it can locate com.example.YourClass and the ; is the classpath separator as it is in Windows. In Unix and clones : should be used.
Create a database in MySQL. Let's create a database javabase. You of course want World Domination, so let's use UTF-8 as well.
CREATE DATABASE javabase DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
Create a user for Java and grant it access. Simply because using root is a bad practice.
CREATE USER 'java'#'localhost' IDENTIFIED BY 'password';
GRANT ALL ON javabase.* TO 'java'#'localhost' IDENTIFIED BY 'password';
Yes, java is the username and password is the password here.
Determine the JDBC URL. To connect the MySQL database using Java you need an JDBC URL in the following syntax:
jdbc:mysql://hostname:port/databasename
hostname: The hostname where MySQL server is installed. If it's installed at the same machine where you run the Java code, then you can just use localhost. It can also be an IP address like 127.0.0.1. If you encounter connectivity problems and using 127.0.0.1 instead of localhost solved it, then you've a problem in your network/DNS/hosts config.
port: The TCP/IP port where MySQL server listens on. This is by default 3306.
databasename: The name of the database you'd like to connect to. That's javabase.
So the final URL should look like:
jdbc:mysql://localhost:3306/javabase
Test the connection to MySQL using Java. Create a simple Java class with a main() method to test the connection.
String url = "jdbc:mysql://localhost:3306/javabase";
String username = "java";
String password = "password";
System.out.println("Connecting database...");
try (Connection connection = DriverManager.getConnection(url, username, password)) {
System.out.println("Database connected!");
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
If you get a SQLException: No suitable driver, then it means that either the JDBC driver wasn't autoloaded at all or that the JDBC URL is wrong (i.e. it wasn't recognized by any of the loaded drivers). Normally, a JDBC 4.0 driver should be autoloaded when you just drop it in runtime classpath. To exclude one and other, you can always manually load it as below:
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
Note that the newInstance() call is not needed here. It's just to fix the old and buggy org.gjt.mm.mysql.Driver. Explanation here. If this line throws ClassNotFoundException, then the JAR file containing the JDBC driver class is simply not been placed in the classpath.
Note that you don't need to load the driver everytime before connecting. Just only once during application startup is enough.
If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException: Communications link failure, then it means that the DB isn't reachable at all. This can have one or more of the following causes:
IP address or hostname in JDBC URL is wrong.
Hostname in JDBC URL is not recognized by local DNS server.
Port number is missing or wrong in JDBC URL.
DB server is down.
DB server doesn't accept TCP/IP connections.
DB server has run out of connections.
Something in between Java and DB is blocking connections, e.g. a firewall or proxy.
To solve the one or the other, follow the following advices:
Verify and test them with ping.
Refresh DNS or use IP address in JDBC URL instead.
Verify it based on my.cnf of MySQL DB.
Start the DB.
Verify if mysqld is started without the --skip-networking option.
Restart the DB and fix your code accordingly that it closes connections in finally.
Disable firewall and/or configure firewall/proxy to allow/forward the port.
Note that closing the Connection is extremely important. If you don't close connections and keep getting a lot of them in a short time, then the database may run out of connections and your application may break. Always acquire the Connection in a try-with-resources statement. Or if you're not on Java 7 yet, explicitly close it in finally of a try-finally block. Closing in finally is just to ensure that it get closed as well in case of an exception. This also applies to Statement, PreparedStatement and ResultSet.
That was it as far the connectivity concerns. You can find here a more advanced tutorial how to load and store fullworthy Java model objects in a database with help of a basic DAO class.
Using a Singleton Pattern for the DB connection is a bad approach. See among other questions: Is it safe to use a static java.sql.Connection instance in a multithreaded system?. This is a #1 starters mistake.
DriverManager is a fairly old way of doing things. The better way is to get a DataSource, either by looking one up that your app server container already configured for you:
Context context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");
or instantiating and configuring one from your database driver directly:
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser("scott");
dataSource.setPassword("tiger");
dataSource.setServerName("myDBHost.example.org");
and then obtain connections from it, same as above:
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ID FROM USERS");
...
rs.close();
stmt.close();
conn.close();
Initialize database constants
Create constant properties database username, password, URL and drivers, polling limit etc.
// init database constants
// com.mysql.jdbc.Driver
private static final String DATABASE_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
private static final String MAX_POOL = "250"; // set your own limit
Initialize Connection and Properties
Once the connection is established, it is better to store for reuse purpose.
// init connection object
private Connection connection;
// init properties object
private Properties properties;
Create Properties
The properties object hold the connection information, check if it is already set.
// create properties
private Properties getProperties() {
if (properties == null) {
properties = new Properties();
properties.setProperty("user", USERNAME);
properties.setProperty("password", PASSWORD);
properties.setProperty("MaxPooledStatements", MAX_POOL);
}
return properties;
}
Connect the Database
Now connect to database using the constants and properties initialized.
// connect database
public Connection connect() {
if (connection == null) {
try {
Class.forName(DATABASE_DRIVER);
connection = DriverManager.getConnection(DATABASE_URL, getProperties());
} catch (ClassNotFoundException | SQLException e) {
// Java 7+
e.printStackTrace();
}
}
return connection;
}
Disconnect the database
Once you are done with database operations, just close the connection.
// disconnect database
public void disconnect() {
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Everything together
Use this class MysqlConnect directly after changing database_name, username and password etc.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class MysqlConnect {
// init database constants
private static final String DATABASE_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
private static final String MAX_POOL = "250";
// init connection object
private Connection connection;
// init properties object
private Properties properties;
// create properties
private Properties getProperties() {
if (properties == null) {
properties = new Properties();
properties.setProperty("user", USERNAME);
properties.setProperty("password", PASSWORD);
properties.setProperty("MaxPooledStatements", MAX_POOL);
}
return properties;
}
// connect database
public Connection connect() {
if (connection == null) {
try {
Class.forName(DATABASE_DRIVER);
connection = DriverManager.getConnection(DATABASE_URL, getProperties());
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
return connection;
}
// disconnect database
public void disconnect() {
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
How to Use?
Initialize the database class.
// !_ note _! this is just init
// it will not create a connection
MysqlConnect mysqlConnect = new MysqlConnect();
Somewhere else in your code ...
String sql = "SELECT * FROM `stackoverflow`";
try {
PreparedStatement statement = mysqlConnect.connect().prepareStatement(sql);
... go on ...
... go on ...
... DONE ....
} catch (SQLException e) {
e.printStackTrace();
} finally {
mysqlConnect.disconnect();
}
This is all :) If anything to improve edit it! Hope this is helpful.
String url = "jdbc:mysql://127.0.0.1:3306/yourdatabase";
String user = "username";
String password = "password";
// Load the Connector/J driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Establish connection to MySQL
Connection conn = DriverManager.getConnection(url, user, password);
Here's the very minimum you need to get data out of a MySQL database:
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/foo", "root", "password");
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM `FOO.BAR`");
stmt.close();
conn.close();
Add exception handling, configuration etc. to taste.
you need to have mysql connector jar in your classpath.
in Java JDBC API makes everything with databases. using JDBC we can write Java applications to
1. Send queries or update SQL to DB(any relational Database)
2. Retrieve and process the results from DB
with below three steps we can able to retrieve data from any Database
Connection con = DriverManager.getConnection(
"jdbc:myDriver:DatabaseName",
dBuserName,
dBuserPassword);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
You can see all steps to connect MySQL database from Java application here. For other database, you just need to change the driver in first step only. Please make sure that you provide right path to database and correct username and password.
Visit http://apekshit.com/t/51/Steps-to-connect-Database-using-JAVA
MySQL JDBC Connection with useSSL.
private String db_server = BaseMethods.getSystemData("db_server");
private String db_user = BaseMethods.getSystemData("db_user");
private String db_password = BaseMethods.getSystemData("db_password");
private String connectToDb() throws Exception {
String jdbcDriver = "com.mysql.jdbc.Driver";
String dbUrl = "jdbc:mysql://" + db_server +
"?verifyServerCertificate=false" +
"&useSSL=true" +
"&requireSSL=true";
System.setProperty(jdbcDriver, "");
Class.forName(jdbcDriver).newInstance();
Connection conn = DriverManager.getConnection(dbUrl, db_user, db_password);
Statement statement = conn.createStatement();
String query = "SELECT EXTERNAL_ID FROM offer_letter where ID =" + "\"" + letterID + "\"";
ResultSet resultSet = statement.executeQuery(query);
resultSet.next();
return resultSet.getString(1);
}
Short and Sweet code.
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDB","root","");
//Database Name - testDB, Username - "root", Password - ""
System.out.println("Connected...");
} catch(Exception e) {
e.printStackTrace();
}
For SQL server 2012
try {
String url = "jdbc:sqlserver://KHILAN:1433;databaseName=testDB;user=Khilan;password=Tuxedo123";
//KHILAN is Host and 1433 is port number
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Driver Loaded");
conn = DriverManager.getConnection(url);
System.out.println("Connected...");
} catch(Exception e) {
e.printStackTrace();
}
Connection I was using some time ago, it was looking like the easiest way, but also there were recommendation to make there if statement- exactly
Connection con = DriverManager.getConnection(
"jdbc:myDriver:DatabaseName",
dBuserName,
dBuserPassword);
if (con != null){
//..handle your code there
}
Or something like in that way :)
Probably there's some case, while getConnection can return null :)
HOW
To set up the Driver to run a quick sample
1. Go to https://dev.mysql.com/downloads/connector/j/, get the latest version of Connector/J
2. Remember to set the classpath to include the path of the connector jar file.
If we don't set it correctly, below errors can occur:
No suitable driver found for jdbc:mysql://127.0.0.1:3306/msystem_development
java.lang.ClassNotFoundException: com.mysql.jdbc:Driver
To set up the CLASSPATH
Method 1: set the CLASSPATH variable.
export CLASSPATH=".:mysql-connector-java-VERSION.jar"
java MyClassFile
In the above command, I have set the CLASSPATH to the current folder and mysql-connector-java-VERSION.jar file. So when the java MyClassFile command executed, java application launcher will try to load all the Java class in CLASSPATH.
And it found the Drive class => BOOM errors was gone.
Method 2:
java -cp .:mysql-connector-java-VERSION.jar MyClassFile
Note: Class.forName("com.mysql.jdbc.Driver"); This is deprecated at this moment 2019 Apr.
Hope this can help someone!
MySql JDBC Connection:
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName","Username","Password");
Statement stmt=con.createStatement();
stmt = con.createStatement();
ResultSet rs=stmt.executeQuery("Select * from Table");
Short Code
public class DB {
public static Connection c;
public static Connection getConnection() throws Exception {
if (c == null) {
Class.forName("com.mysql.jdbc.Driver");
c =DriverManager.getConnection("jdbc:mysql://localhost:3306/DATABASE", "USERNAME", "Password");
}
return c;
}
// Send data TO Database
public static void setData(String sql) throws Exception {
DB.getConnection().createStatement().executeUpdate(sql);
}
// Get Data From Database
public static ResultSet getData(String sql) throws Exception {
ResultSet rs = DB.getConnection().createStatement().executeQuery(sql);
return rs;
}
}
Download JDBC Driver
Download link (Select platform independent): https://dev.mysql.com/downloads/connector/j/
Move JDBC Driver to C Drive
Unzip the files and move to C:\ drive. Your driver path should be like C:\mysql-connector-java-8.0.19\mysql-connector-java-8.0.19
Run Your Java
java -cp "C:\mysql-connector-java-8.0.19\mysql-connector-java-8.0.19\mysql-connector-java-8.0.19.jar" testMySQL.java
testMySQL.java
import java.sql.*;
import java.io.*;
public class testMySQL {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/db?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("show databases;");
System.out.println("Connected");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Programmatic login with liberty profile without password

I try to migrate our application from WAS 8.0 to Liberty Profile at the moment.
In our application I need the possibility to do a programmatic login without having the password of the user.
In WAS 8.0 this was done with the following code snippet:
import com.ibm.websphere.security.auth.WSSubject;
import com.ibm.ws.security.core.ContextManagerFactory;
import com.ibm.websphere.security.auth.callback.WSCallbackHandlerImpl;
public class SecurityConfigJaasWasImpl implements ISecurityConfig {
public Object doAsWithoutPwd(String user, String[] roles, final ISecuredCode code) throws Exception {
final String mName ="doAs(String, String[], ISecuredCode)";
Object ret = null;
try {
if (code != null) {
ret = WSSubject.doAs(ContextManagerFactory.getInstance().login("REALM", user), new PrivilegedExceptionAction() {
/* (non-Javadoc)
* #see java.security.PrivilegedExceptionAction#run()
*/
public Object run() throws Exception {
return code.run();
}
});
}
} catch (LoginException e) {
throw new SecurityConfigException("Error login user " + user);
}
}
Unfortunately the class ContextManagerFactory is not known in Liberty.
All examples for programmatic login with liberty profile are using WSCallbackHandlerImpl to do a Jaas login. But for that I need to know the password of the user.
Is there any possibility to do something similar to my WAS 8.0 code in liberty profile?
I had this same problem when porting our application from WAS-ND 7 to Liberty. Unfortunately, there is no way to perform a programmatic login on Liberty without having access to the user's password. I have an open PMR with IBM on this (25293,082,000), and I was told that the feature is "under consideration". I also have an RFE open on this:
https://www.ibm.com/developerworks/rfe/execute?use_case=viewRfe&CR_ID=100438

Orientdb partitioned graph java implementation

I've got a backend Spring application and Orientdb graph database. I use Tinkerpop Frames to map orientdb vertices to java objects and OPS4J for spring transaction management. Now I want to implement there a multitenancy where several customers (tenants) uses this one application instance. This application completely works on REST principles and it is opened to several Angular applications - each per customer. So there's as many frontend Angular applications as our customers and only one backend REST Spring application. Backend recognize the tenant from a HTTP request.
Now I'm not sure about the best solution...
First solution
When I read the Orientdb documentation, I found there a way how to implement multitenancy in orientdb - http://orientdb.com/docs/2.1/Partitioned-Graphs.html. However I don't know how to use it through the Java API unless I don't want to create a new database connection for each request. Because right now the spring transaction manager takes connections from connection pool which is centrally set in Spring transaction management configuration. I didn't find any Java example to this.
Spring transaction management config:
#Configuration
#EnableTransactionManagement
public class TransactionConfig {
#Bean
#Qualifier("graphDbTx")
public OrientTransactionManager graphDbTransactionManager() {
OrientTransactionManager bean = new OrientTransactionManager();
bean.setDatabaseManager(graphDatabaseFactory());
return bean;
}
#Bean
public OrientBlueprintsGraphFactory graphDatabaseFactory() {
OrientBlueprintsGraphFactory dbf = new OrientBlueprintsGraphFactory();
dbf.setMaxPoolSize(6);
dbf.setUrl(DbConfig.DATABASE_URL);
dbf.setUsername("admin");
dbf.setPassword("admin");
return dbf;
}
#Bean
public FramedGraphFactory framedGraphFactory() {
return new FramedGraphFactory(new JavaHandlerModule());
}
}
Getting connection:
protected FramedGraph<OrientGraph> framedGraph() {
return framedGraphFactory.create(gdbf.graph());
}
Second solution
Another solution is to use the Tinkerpop
PartitionGraph
class which works on Orientdb but I didn't find any sentence about this possibility in Orientdb documentation. Just this in Tinkerpop - https://github.com/tinkerpop/blueprints/wiki/Partition-Implementation. It works but in the end it just creates a not indexed property in every orientdb vertex so I'm afraid about performance of querying here.
Does anyone have any experiences with this? Any suggestion?
Using the Java API to create a partitioned DB (if I understand what you're interested in) macro steps are:
get connection (using the pool the istance of db are reused);
modify class V and E; create new user enable to write;
when you log in the db, user1 can write Vertices, invisible to the
user2 and contrary;
//WRITE IN YOUR CONTROLLER: CREATE USER ENABLE TO WRITE ON DB ..............
Connection con = new Connection();
OrientGraph noTx = con.getConnection();
//create partition
noTx.begin();
noTx.command(new OCommandSQL("ALTER CLASS V superclass orestricted")).execute();
noTx.command(new OCommandSQL("ALTER CLASS E superclass orestricted")).execute();
noTx.commit();
//create different users
noTx.begin();
String ridRule = "";
Iterable<Vertex> rule = noTx.command(new OCommandSQL("select from ORole where name = 'writer'")).execute();
ridRule = rule.iterator().next().getId().toString();
noTx.command(new OCommandSQL("INSERT INTO ouser SET name = 'user1', status = 'ACTIVE', password = 'user1', roles = ["+ridRule+"]")).execute();
noTx.command(new OCommandSQL("INSERT INTO ouser SET name = 'user2', status = 'ACTIVE', password = 'user2', roles = ["+ridRule+"]")).execute();
noTx.commit();
//will not close the graph instance, but will keep open and available for the next requester
noTx.shutdown();
//finally To release all the instances and free all the resources
con.clodeAllConnect();
//WRITE IN YOUR CONTROLLER: LOGIN WITH USER APPROPRIATE .....................
//CODE to login with user1 or user2, CREATE VERTEX SET label = 'food', name = 'Pizza' etc....
}
//beans
public static class Connection {
private OrientGraphFactory factory = null;
public Connection() {
//recyclable pool of instances
factory = new OrientGraphFactory("remote:localhost/blog").setupPool(1, 10);
}
//return the connection
public OrientGraph getConnection() {
OrientGraph txGraph = factory.getTx();
return txGraph;
}
public void clodeAllConnect(){
factory.close();
}
}
To adapt these steps and insert them in Spring might be useful this link that is OrientDB - spring implementation. it isn't much but I hope will be of help.

Connecting to Google cloud sql from Java stand alone application

I want to write a java stand alone application to connect to google cloud sql - MySql database. I could find samples for app client but not for a stand alone java application.
When I tried to do this, I get the following error.
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:google:mysql://IP:Instance_name?user=user_name");
Statement st = con.createStatement();
ResultSet rs = con.createStatement().executeQuery("SELECT 1 + 1");
It fails with error:
No suitable driver found for jdbc:google:mysql:..
I see some answers where they have asked to enabled mysql connector. But it is the case with app engine project. How do I do it with stand alone application?
You can just use the standard mysql connector to connect to cloud sql instance: e.g:
DriverManager.getConnection("jdbc:mysql://IP:Instance_name?user=user_name");
You can check this link https://cloud.google.com/sql/docs/external for more information.
We can simply use the standard mysql java connector to connect to cloud sql form a standalone java application.
Follow the below code snippet. This should help you to connect to database seamlessly.
class.forName(com.mysql.jdbc.Driver);
String connectionUrl = "jdbc:mysql//<public-ip>/<database>?useSSL=false";
Connection conn = DriverManager.getConnection(connectionUrl, user, password);
Before you do this make sure you get your ipaddress from internet and add the same under the path : google cloud -> sql -> sqlinstance -> connections -> networking -> Authorized networks.
Click here to see the google cloud mysql configuration
Edit inside <> before running your code
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLNonTransientConnectionException;
import java.sql.Statement;
/**
* A sample app that connects to a Cloud SQL instance and lists all available tables
in a database.
*/
public class Cloud_sql {
public static void main(String[] args) throws SQLNonTransientConnectionException
,IOException, SQLException {
String instanceConnectionName = <Your instanceConnectionName>;
String databaseName = <Database name from which u want to list tables>;
String IP_of_instance = <IP address of the instance>;
String username = <mysql username>;
String password = <mysql password>;
String jdbcUrl = String.format(
"jdbc:mysql://%s/%s?cloudSqlInstance=%s"
+ "&socketFactory=com.google.cloud.sql.mysql.SocketFactory&useSSL=false",
IP_of_instance,
databaseName,
instanceConnectionName);
Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery("SHOW TABLES");
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
}catch(Exception e){
e.printStackTrace();
}
}
}

What is the default username and password for h2 when there's nothing explicit in JDBC?

From a program, I created a H2 database without specifying any user or password in the JDBC URL.
Now I'm trying to access that database with the Script tool. The doc says to use -user sa in the default case. That doesn't work, and it still doesn't work if I either add -password sa or remove -user. What am I missing?
/opt/h2/bin java -cp h2-1.3.161.jar org.h2.tools.Script -url jdbc:h2:/data/jug/jas-coref.h2 -user sa -password sa -script /data/jug/ris-start.sql
Exception in thread "main" org.h2.jdbc.JdbcSQLException: Wrong user name or password [28000-161]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:329)
at org.h2.message.DbException.get(DbException.java:169)
at org.h2.message.DbException.get(DbException.java:146)
at org.h2.message.DbException.get(DbException.java:135)
at org.h2.engine.Engine.validateUserAndPassword(Engine.java:301)
at org.h2.engine.Engine.createSessionAndValidate(Engine.java:146)
at org.h2.engine.Engine.createSession(Engine.java:121)
at org.h2.engine.Engine.createSession(Engine.java:28)
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:285)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:110)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:94)
at org.h2.Driver.connect(Driver.java:72)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at org.h2.tools.Script.execute(Script.java:152)
at org.h2.tools.Script.execute(Script.java:133)
at org.h2.tools.Script.runTool(Script.java:101)
at org.h2.tools.Script.main(Script.java:51)
Well, duh, that didn't take long.
The answer is -user "".
This might work:
name = "sa"
password = ""
In case you got stuck with the default non-blank user when running the client, the full set of parameters will get you past that:
java -cp <path_to_h2>\h2.jar org.h2.tools.Shell -url "jdbc:h2:file:<jdbc_url>" -driver "org.h2.Driver" -user "" -password ""
In your application.properties file please add
spring.datasource.username=username
spring.datasource.password=password
hope it helps
Note: If you are getting this error when trying to login via Intellij, you need to enable MIXED_MODE. See this answer for more details: Connect to H2 database using IntelliJ database client
in my case i had mispelled the username and password properties, so i assume spring tried to use the defaults which didn't work
I don't know if it helps, but I had a case in which, using H2 in memory for testing, the connection failed if I tried to connect with different credentials multiple times. This test:
public class H2Test {
#Test
public void differentCredentials() throws SQLException {
connect("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "foo", "");
connect("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "bar", "");
}
private void connect(
String url, String username, String password
) throws SQLException {
Properties props = new Properties();
props.put("user", username);
props.put("password", password);
DriverManager.getConnection(url, props);
}
}
fails with error:
org.h2.jdbc.JdbcSQLException: Wrong user name or password [28000-196]
This instead doesn't:
public class H2Test {
#Test
public void sameCredentials() throws SQLException {
connect("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "foo", "");
connect("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "foo", "");
}
private void connect(
String url, String username, String password
) throws SQLException {
Properties props = new Properties();
props.put("user", username);
props.put("password", password);
DriverManager.getConnection(url, props);
}
}
That said, I couldn't find a piece of documentation that confirms this behaviour.
The user name is: sa and password not required
try this:
java -cp h2*.jar org.h2.tools.Script -user "sa" -password "" -url "jdbc:h2:path_to_your_db_file"

Resources