how can i connect from java to mysql server? - java

The error is that I cant open the connection to mysql database, it must be an error in parameters but I am confused , I have no idea where is the problem.

First you need to create a MySQL schema. Secondly, use JDBC to connect to your recently created database (via localhost - make sure you get the user/password right).
After that you should use DAO-like classes. I'll leave here a Connect class:
public class Connect {
private static final String USERNAME = "root";
private static final String PASSWORD = "12345";
private static final String URL = "localhost";
private static final String SCHEMA = "new_schema";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection connect() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://"+URL+"/"+SCHEMA+"?user="+USERNAME+"&password="+PASSWORD);
}
}
After you have the Connect class, you should connect to the database using Connection c = Connect.connect(). Here's a class that implements it.
public static List<Album> list() throws SQLException {
Connection c = Connect.connect();
ResultSet rs = c.createStatement().executeQuery("SELECT * FROM Albums");
List<Album> list = new ArrayList<>();
while (rs.next()) {
String name = rs.getString("nome"); // first table column (can also use 1)
String artist = rs.getString("artista"); // second table column (can also use 2)
Album a = new Album(name, artist);
list.add(a);
}
return list;
}
It should also give you an insight as to how you should use SQL commands.
If you'd like a more in-depth help you should post the code you used, otherwise it's difficult to give you a more "to-the-point" explanation.

JDBC URLs can be confusing. Suggest you try using a SQL tool that understands the JDBC protocol (such as the database development perspective in Eclipse) to validate the URL and make sure you can connect to the database before you start coding. Cutting and pasting a URL known to work into your code can avoid many problems.

Related

What is the best way to get database name use java metadata

In my application using different databases (postgres, mssql, oracle ...). What is the best way to get database name use metadata. I was trying to use this approach:
try (final Connection connection = jdbcTemplate.getDataSource().getConnection()) {
final DatabaseMetaData metaData = connection.getMetaData();
final String databaseName = StringUtils.substringAfterLast(connection.getMetaData().getURL(), "/");
It works in this case:
spring.datasource.url=jdbc:mysql://localhost:3306/2022_2
But in this case it doesn't work:
spring.datasource.url=jdbc:sqlserver://localhost:1433;DatabaseName=test_mssql;encrypt=true;trustServerCertificate=true;
You may consider using Connection#getCatalog() for your case.
Please see the following example below:
try (final Connection connection = jdbcTemplate.getDataSource().getConnection()) {
String databaseName = connection.getCatalog();
} catch (SQLException e) {
e.printStackTrace();
}

How to switch between different database users with different permissions, directly inside my application on Java?

So I'm using Java and MySQL, I created a database with different roles (user/manager/admin etc....) By default, I'm connected as a simple user, but how can I switch my user to the super admin after he authenticates?
Because right now, my connection with MySQL is made in a private constructor with private methods, so at first I thought about putting setters, but I can't access them given that I can't instantiate an object from my class with the private constructor.
ConnexionMySQL.java:
private ResourceBundle bundle =
ResourceBundle.getBundle("domaine.properties.config");
private String url = bundle.getString("sgbd.url");
private String driver = bundle.getString("sgbd.driver");
private String mysqlUser = bundle.getString("sgbd.login");
private String mysqlPassword = bundle.getString("sgbd.password");
private ConnexionMysql(){
try {
session = doSshTunnel(this.sshUser, this.sshPassword, this.sshHost, this.sshPort, this.url, this.sshLocalPort,this.sshRemotePort);
System.out.println("Opened SSH on " + sshHost);
Class.forName(driver);
connect = DriverManager.getConnection(url, mysqlUser ,mysqlPassword);
System.out.println("connect� Mysql");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static Connection getInstance(){
if(instance == null){
instance = new ConnexionMysql();
System.out.println("INSTANCIATION DE LA CONNEXION SQL ! ");
}
else{
System.out.println("CONNEXION SQL EXISTANTE ! ");
}
return connect;
}
public static void disconnect(){
try {
connect.close();
session.disconnect();
instance = null;
System.out.println("Deconnexion r�ussie");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
I have another config.properties file in which I specified the login and password.
But what if now I wanna change those values in a controller for example after a user authenticates ?
I would say that the easiest way to solve this problems will be to make as many clases as roles you want to create (of course if you want to leave your constructor private).
In my opinion it should look something like this:
ConnexionMySQLuser;
ConnexionMySQLmanager;
ConnexionMySQLadmin;
Of course if you have numerous of roles it can create problems in future.

Does MariaDB disconnect automatically or Should i have to disconnect Manually?

I got to use MariaDB for my University Project.
it's my first time doing it, so I dont't know well how to use and code JDBC Driver and mariaDB.
Now I'm implementing the code in many places while looking at examples.
As I see, All the examples seems to creating Statement and making connection by using "DriverManager.getConnection"
Now I have a question.
I'm going to create a DBmanager Class that can connect, create tables, execute queries, and execute the code that updates data on tables in a single line.
I thought all the examples would run alone in one method and came from different places, so I could only try a new connection and create a code that would not close. But I have a gut feeling that this will be a problem.
Is there any way I can leave a connection connected at a single connection to send a command, and disconnect it to DB.disconnect()? And I'd appreciate it if you could tell me whether what I'm thinking is right or wrong.
The code below is the code I've written so far.
I am sorry if you find my English difficult to read or understand. I am Using translator, So, my English could not be display as I intended.
import java.sql.*;
import java.util.Properties;
public class DBManager {
/*********INNITIAL DEFINES********/
final static private String HOST="sumewhere.azure.com";//Azure DB URL
final static private String USER="id#somewhere";//root ID
final static private String PW="*****";//Server Password
final static private String DRIVER="org.mariadb.jdbc.Driver";//DB Driver info
private String database="user";
/***************API***************/
void setDB(String databaseinfo){
database=databaseinfo;
}
private void checkDriver() throws Exception
{
try
{
Class.forName("org.mariadb.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("MariaDB JDBC driver NOT detected in library path.", e);
}
System.out.println("MariaDB JDBC driver detected in library path.");
}
public void checkOnline(String databaseinfo) throws Exception
{
setDB(databaseinfo);
this.checkDriver();
Connection connection = null;
try
{
String url = String.format("jdbc:mariadb://%s/%s", HOST, database);
// Set connection properties.
Properties properties = new Properties();
properties.setProperty("user", USER);
properties.setProperty("password", PW);
properties.setProperty("useSSL", "true");
properties.setProperty("verifyServerCertificate", "true");
properties.setProperty("requireSSL", "false");
// get connection
connection = DriverManager.getConnection(url, properties);
}
catch (SQLException e)
{
throw new SQLException("Failed to create connection to database.", e);
}
if (connection != null)
{
System.out.println("Successfully created connection to database.");
}
else {
System.out.println("Failed to create connection to database.");
}
System.out.println("Execution finished.");
}
void makeCcnnection() throws ClassNotFoundException
{
// Check DB driver Exists
try
{
Class.forName("org.mariadb.jdbc");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("MariaDB JDBC driver NOT detected in library path.", e);
}
System.out.println("MariaDB JDBC driver detected in library path.");
Connection connection = null;
}
public void updateTable(){}
public static void main(String[] args) throws Exception {
DBManager DB = new DBManager();
DB.checkOnline("DB");
}
}
For a studying project it's okay to give a connection from your DB Manager to client code and close it there automatically using try-with-resources construction.
Maybe you will find it possible to check Connection Pool tools and apply it further in your project or use as example (like HikariCP, here is a good introduction).
Read about Java try with resources. I think that this link could be usefull for your problem.
JDBC with try with resources

Timeout while receiving message with Mongo Connection pooling using java

In production we are connecting with a MongoDB using Java (connection pooling). Every day we are getting almost 500 requests with the error below (MongoSocketReadTimeoutException) and we are not using any complex query. Could it be stale Mongo connections?
I didn't see a problem with our code or MongoDB slowness. Please review my code below and suggest if any parameters need to be added or anything needs to be changed.
at 2018-03-07 19:52:43 ERROR ::Error while connecting the Mongo DB {}
com.mongodb.MongoSocketReadTimeoutException: Timeout while receiving message
at com.mongodb.connection.InternalStreamConnection.translateReadException(InternalStreamConnection.java:474)
at com.mongodb.connection.InternalStreamConnection.receiveMessage(InternalStreamConnection.java:225)
at com.mongodb.connection.UsageTrackingInternalConnection.receiveMessage(UsageTrackingInternalConnection.java:102)
at com.mongodb.connection.DefaultConnectionPool$PooledConnection.receiveMessage(DefaultConnectionPool.java:435)
at com.mongodb.connection.CommandProtocol.execute(CommandProtocol.java:112)
at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:159)
at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:286)
at com.mongodb.connection.DefaultServerConnection.command(DefaultServerConnection.java:173)
at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:215)
at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:206)
at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:112)
at com.mongodb.operation.FindOperation$1.call(FindOperation.java:487)
at com.mongodb.operation.FindOperation$1.call(FindOperation.java:482)
at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:239)
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:212)
at com.mongodb.operation.FindOperation.execute(FindOperation.java:482)
at com.mongodb.operation.FindOperation.execute(FindOperation.java:79)
at com.mongodb.Mongo.execute(Mongo.java:772)
at com.mongodb.Mongo$2.execute(Mongo.java:759)
at com.mongodb.FindIterableImpl$FindOperationIterable.first(FindIterableImpl.java:207)
at com.mongodb.FindIterableImpl.first(FindIterableImpl.java:148)
at com.tecnotree.bom.validation.dao.MongoManager.getJsonObject(MongoManager.java:88)
at com.tecnotree.bom.validation.dao.CustomerMasterDao.getService(CustomerMasterDao.java:48)
at com.tecnotree.bom.validation.service.ValidationService.processValidation(ValidationService.java:214)
at com.tecnotree.bom.validation.service.ValidationService.processRequest(ValidationService.java:125)
at sun.reflect.GeneratedMethodAccessor185.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvid
er.java:205)
Code
public class ConnectionManager {
private ConnectionManager() {
}
private static final Logger logger = LoggerFactory.getLogger(ConnectionManager.class);
private static MongoClient mongoClient = null;
private static String connections = null;
private static String connectionTimeOut = null;
private static String socketTimeOut = null;
private static String serverSelectionTimeOut = null;
private static String URL = null;
private static String username = null;
private static String password = null;
private static String hostname = null;
private static String port = null;
private static String maxConnectionIdleTime = null;
private static String minConnectionsPerHost = null;
private static String maxConnectionLifeTime = null;
private static String dbName = null;
static {
dbName = ValidationProperties.getValue("clm.db.dbName");
mongoClient = getCLMSecondaryMongoConnection();
}
private static MongoClient getCLMSecondaryMongoConnection() {
connections = ValidationProperties.getValue("clm.db.connectionsPerHost");
connectionTimeOut = ValidationProperties.getValue("clm.db.connectTimeoutMS");
socketTimeOut = ValidationProperties.getValue("clm.db.socketTimeOut");
serverSelectionTimeOut = ValidationProperties.getValue("clm.db.serverSelectionTimeOut");
username = ValidationProperties.getValue("clm.db.userName");
password = ValidationProperties.getValue("clm.db.password");
hostname = ValidationProperties.getValue("clm.db.hostname");
port = ValidationProperties.getValue("clm.db.portnumber");
maxConnectionIdleTime = ValidationProperties.getValue("clm.db.maxConnectionIdleTime");
minConnectionsPerHost = ValidationProperties.getValue("clm.db.minConnectionsPerHost");
try {
List<MongoCredential> creds = new ArrayList<MongoCredential>();
creds.add(MongoCredential.createCredential(username, dbName, password.toCharArray()));
/*creds.add(MongoCredential.createMongoCRCredential(username, dbName, password.toCharArray()));*/
MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder();
optionsBuilder.connectTimeout(Integer.parseInt(connectionTimeOut));
optionsBuilder.serverSelectionTimeout(Integer.parseInt(serverSelectionTimeOut));
optionsBuilder.socketTimeout(Integer.parseInt(socketTimeOut));
optionsBuilder.connectionsPerHost(Integer.parseInt(connections));
optionsBuilder.maxConnectionIdleTime(Integer.parseInt(maxConnectionIdleTime));
optionsBuilder.minConnectionsPerHost(Integer.parseInt(minConnectionsPerHost));
if(Boolean.valueOf(ValidationProperties.getValue("clm.db.useSecondaryMongoForRead"))) {
logger.info("Read is going for secondary mongoDB");
optionsBuilder.readPreference(ReadPreference.secondaryPreferred());
}
MongoClientOptions options = optionsBuilder.build();
mongoClient = new MongoClient(new ServerAddress(hostname, Integer.parseInt(port)), creds, options);
} catch (Exception e) {
logger.error("Error while connecting the Mongo DB {}", e);
}
return mongoClient;
}
public static MongoClient getMongoClient() {
return mongoClient;
}
In your code you are setting various MongoClientOptions, but you do not say what values you are using. Most likely one of the settings is causing the problem. My first guess would be that socketTimeout is too small, my second guess would be that connectionsPerHost is smaller than the maximum number of concurrent requests you receive in production.
I assume that testing in your production environment is not an option, so the first thing you should do is try and reproduce the problem in a test environment. You can use the free JMeter tool to reproduce a certain load to your server. Use it's ramp-up feature to see if your problems start once you reach a certain load or if they occur at random.
If you still have trouble finding out what exactly causes the problems, you can also try to comment out all your optionBuilder settings (so you'll be using all default settings). If that fixes the problem, then you can set back your configuration options one-at-a-time to see which is the problematic one.
You must remove hibernate dependency from your project.
I faced this problem and that was the solution.

Java Application cannot connect to mysql database in openshift

everyone!
I'm using the free account of OpenShift by RedHat PaaS to host my java aplication. For tests, I created an aplication that just get two user info (login and password) in the index.jsp, then it search into database and redirect to the success page(message "Good morning/afternoot/night, ${user.name}") or a failure page (message "You're not registred"). I also created a database, called autenticacao, with one table called usuario (user) in phpMyAdmin and this works well in localhost. But in the openshift, my servlet receives a null 'usuario' (user) object from the method obter(String login, String senha), that should get a result of one select query. I think it doesnt create a database connection. I've really tried so hard to make it works, and seen too many solutions in foruns (also here in stackoverflow) and nothing works.
Im using some design patterns but I think it's not a problem.
This is my DatabaseLocator.java:`
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*
* #author Luiz
*/
public class DatabaseLocator {
private static DatabaseLocator instance = new DatabaseLocator();
public static DatabaseLocator getInstance() {
return instance;
}
private DatabaseLocator() {
}
public Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
String user = System.getenv("OPENSHIFT_MYSQL_DB_USERNAME");
String password = System.getenv("OPENSHIFT_MYSQL_DB_PASSWORD");
String url = System.getenv("OPENSHIFT_MYSQL_DB_URL");
String host = System.getenv("OPENSHIFT_MYSQL_DB_HOST");
String port = System.getenv("OPENSHIFT_MYSQL_DB_PORT");
Connection conn
= DriverManager.getConnection(host+port+"/autenticacao",user,password);
return conn;
}
}
The error happens when I try create a connection in st = conn.createStatement(); part.
public Usuario obterUsuario(String login, String password) {
Usuario usuario = null;
Connection conn = null;
Statement st = null;
try {
conn = DatabaseLocator.getInstance().getConnection();
st = conn.createStatement();
ResultSet rs = st.executeQuery("select * from usuario where login='" + login + "' and senha='" + password + "'");
rs.first();
usuario = instanciar(rs);
} catch (ClassNotFoundException cnf) {
} catch (SQLException ex) {
System.out.println(ex.getCause());
}
return usuario;
}
public static Usuario instanciar(ResultSet rs) throws SQLException, ClassNotFoundException {
Usuario usuario = new Usuario();
usuario.setLogin(rs.getString("login"));
usuario.setSenha(rs.getString("senha"));
//other rs fields that would be setted to user object
return user;
}
}
This code is in portuguese, so if any word doesnt make sense, you can ask me. I have some other classes, I can show it if you want.
So, how can I connect to my database? Can you help me? Thanks.
Are you still facing this problem? If yes then try to make your openshift application non-scalable if it's set to scalable and vise versa if not. I've encountered this before I just don't remember exactly. In your case, port-forwarding in openshift will help if you don't want to change the scalability of your application. I use Jboss Dev Studio for creating my jboss app in openshift, in case you also want jboss.
You need to change the line:
Connection conn = DriverManager.getConnection(host+port+"/autenticacao",user,password);
It should be:
Connection conn = DriverManager.getConnection("jdbc:mysql:"+host+":"+port+"/autenticacao",user,password);

Categories