Java Application cannot connect to mysql database in openshift - java

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);

Related

I can't figure out how to connect Java application an Android with database MySQL

I want to make an Android app. Please tell me how to create and configure a configuration class to send queries to the database. The database is located in the cloud. What should this class look like?
Let's say a client clicks on a button and a list of building materials is shown to him. Clicks on another button, a list of applications appears.
I understand that you need to use jdbc, but it's not clear how to do it correctly ((
I use Intellij idea.
public class DatabaseController {
private String host = "jdbc:mysql://*********/*********?autoReconnect=true&useSSL=false";
private String DB_name = "*********";
private String username = "*********";
private String password = "*********";
private Connection getDbConn() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection(host,username, password);
}
public void insertTask(String task) throws SQLException, ClassNotFoundException {
PreparedStatement prSt = getDbConn().prepareStatement("DELETE FROM User WHERE id = 1");
prSt.executeUpdate();
}
public ArrayList<String> geTasks() throws SQLException, ClassNotFoundException {
String sql = "SELECT * FROM User";
Statement statement = getDbConn().createStatement();
ResultSet resultSet = statement.executeQuery(sql);
ArrayList<String> tasks = new ArrayList<>();
while (resultSet.next()) {
tasks.add(resultSet.getString("task"));
}
return tasks;
}
}
an exception is thrown
Exception in thread "main" java.sql.SQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
dependency
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>

How to connect a Java application to db4free.net using JDBC?

I'm doing a college project where we have to build a fully functioning Java application, complete with a basic user login system using JDBC.
The basic user login system works fine when used on XAMPP's MariaDB MySQL branch via localhost.
Obviously, the system wouldn't work outside of this particular network, so I looked around for ways to allow me to host a MySQL database online at all times so regardless of where I go, this basic user login system works and can be shown to anyone who's interested.
I then found db4free.net, and so far everything looks in order - PHPMyAdmin works, and I managed to successfully export and import the database with the usernames and passwords from the localhost version to db4free's version.
But I'm having trouble on how to actually point my application to connect to db4free's systems so the login system works as intended.
Here's the "connection module" Java class that handles the connection:
package com.fixer.dal;
import java.sql.*;
public class Connection_Module {
public static Connection connector(){
java.sql.Connection cnx = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://db4free.net:3306/db_fixer";
String user = "myuser";
String password = "mypassword";
try {
Class.forName(driver);
cnx = DriverManager.getConnection(url, user, password);
return cnx;
} catch (Exception e) {
return null;
}
}
}
And here's the function that checks with the database to see if the username and password match with the recorded data (and if it does, it closes the login screen and opens the "main" screen):
Connection cnx = null;
PreparedStatement pst = null;
ResultSet rs = null;
public void login(){
String sql = "select * from usertable where username=? and password=?";
try {
pst = cnx.prepareStatement(sql);
pst.setString(1, Screen_Login_Username_Field.getText());
pst.setString(2, Screen_Login_Password_Field.getText());
rs = pst.executeQuery();
if(rs.next()){
Screen_Main Main = new Screen_Main();
Main.setVisible(true);
this.dispose();
cnx.close();
}else{
JOptionPane.showMessageDialog(null, "Invalid user or password.");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
And that's mostly my problem. db4free.net gave me a host ("db4free.net") and a port ("3306"), but I don't know exactly where do they go. I've tried some methods to get it to work based off other questions here but none successfully connected me to my database on their systems.
What am I doing wrong?
I just created a database (for the first time) in db4free.com and I used:
MySQL 8.x JDBC driver (I used the JDBC driver 8.0.11).
The URL is:
jdbc:mysql://db4free.net:3306/database-name
In MySQL 8.x, however, it's better to add the following parameters to avoid dealing with tons of warnings:
jdbc:mysql://db4free.net:3306/database-name?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false
It worked like a charm at once. Did you confirm the email they sent? Is your account active? Are you using the JDBC driver 8.x?

how can i connect from java to mysql server?

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.

servlet netbeans mysql connect

I am new to sql and I am using netbeans and mysql.
I am trying to make a servlet that will check login details against a database.
I found some code oline but it doesn't interact with the database. Also every example I find doesn't work either. What am I doing wrong.
Here is some of the code
package login;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
/**
*
* #author john
*/
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String userName = request.getParameter("userName");
if (Validate.CheckUser(userName)) {
RequestDispatcher rs = request.getRequestDispatcher("Welcome");
rs.forward(request,
response
);
}
else
{
RequestDispatcher rs = request.getRequestDispatcher("index.html");
rs.include(request , response);
}
}
}
AND
package login;
import java.sql.*;
/**
*
* #author john
*/
public class Validate {
public static boolean CheckUser(String userName) {
boolean st = false;
try {
Class.forName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewdatabase?zeroDateTimeBehavior=convertToNull", "root", "admin");
PreparedStatement ps = con.prepareStatement("SELECT userName FROM userData where userName=?");
ps.setString(1, userName);
ResultSet rs = ps.executeQuery();
st = rs.next();
} catch (Exception e) {
e.printStackTrace();
}
return st;
}
}
What are the extra steps I need to take to get this to connect to the data base. I am using the latest version of netbeans.
I have already put the 5.1.26-bin.jar file into the library.
Mynewdatabase is running just fine(I connected using a connection pool a JSP before in a different application).
This application will not connect to the data base though. I am not using a connection pool here.
Any help would be great.
Connecting to a database has nothing at all do with NetBeans or servlets. I'd advise that you get the database class working before adding in unnecessary complications.
It'd help if you'd post an error. "Not working" isn't helpful.
Your driver class for MySQL doesn't look correct to me. Should be com.mysql.jdbc.Driver.
But there's lots more wrong with your code than that.
Your query brings back a username. No password? Not useful.
No application should access a database using the root admin password. Create an ID for the app and only GRANT sufficient permission to perform its tasks.
You don't close resources in your method. You'll have problems if you ever get this to run.
Come back if you get it to work at all.
To retrieve from database you should use this way
while(rs.next())
{
String coulm1=rs.getString(1);
String column2=rs.getString(2);
}
The code should be like this:
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewdatabase", "root", "admin");
You will also need to add mysql driver jar file to the classpath. Firstly try to connect with database with simple parameters in database url, then move to the complex ones when you are fully ready!

Java to mysql jdbc connection problems

I'm new with getting a java applet to connect to a mysql database. This is my first time attempting to do so.
I've researched a lot and have seen lots of tutorials, but I'm still facing problems.
Since my java applet goes to a browser, I did sign it.
I've also been using jdbc and the jar file has been imported properly to my library.
I've also been using 000webhost.com and have been trying to connect to the database from both the IDE and the browser.
I also got two of my friends to help me. One of them had to go early and the other don't know where I went wrong.
Here is my codes:
http://prntscr.com/oagfi
I've come to the conclusion that the DriverManager.getConnection(...) is whats giving me problems.
The error reads...
http://prntscr.com/oaetz
I have also tried looking up the cause but still no luck.
Is there anything I can do to fix this problem? I'm curious of what this cause mean and why I'm having trouble.
If you are on free 000webhost accounts than you cant access your database outside your host account.
Check the version of JDBC Connector you are using. Also following link will help you to do JDBC Connection -
Connect Java to a MySQL database
Are you behind a firewall/proxy server? If so, does it permit outgoing connections on port 3306 you're using? This was a problem I had once, our corporate firewall was so crippled we could only talk out via the http /https ports.
From Applet (if my memory not fail), you must use Signed code and/or you can only connect to remotehost from Applet was downloaded... if not, security exceptions are throwed. (applets run on a limited/restricted sandbox)
/* RegistrationDAO*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.tcs.ignite.connectionname.DAO;
import com.tcs.ignite.connectionname.bean.Register;
import com.tcs.ignite.connectionname.util.Eyeconnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class RegisterDAO {
private Connection connection;
private connectionnamecon;
public RegisterDAO() {
con = new connectionname();
}
public boolean insertRecords(Register rg) throws Exception {
connection = con.openConnection();
String select="select * from register";
PreparedStatement ps=connection.prepareStatement(select);
ResultSet rs=ps.executeQuery();
while(rs.next())
{
String email=rs.getString("user_email");
if(rg.getUser_email().equals(email))
{
return false;
}
}
ps.close();
String query = "insert into register(user_Fname,user_Lname,password,confirm_pass,contact_no,user_email,user_address,user_pincode) VALUES (?,?,?,?,?,?,?,?)";
ps = connection.prepareStatement(query);
ps.setString(1, rg.getUser_Fname());
ps.setString(2, rg.getUser_Lname());
ps.setString(3, rg.getPassword());
ps.setString(4, rg.getConfirm_pass());
ps.setString(5, rg.getContact_no());
ps.setString(6, rg.getUser_email());
ps.setString(7, rg.getUser_address());
ps.setString(8,rg.getUser_pincode());
int rowcount = ps.executeUpdate();
con.closeConnection();
if (rowcount == 0) {
return false;
} else {
return true;
}
}
}
/*
RegistrationManager*/
*/
package com.tcs.ignite.connectionname.Manager;
import com.tcs.ignite.connectionname.DAO.RegisterDAO;
import com.tcs.ignite.connectionname.bean.Register;
public class RegisterManager {
public boolean insertManager(Register rg) throws Exception {
RegisterDAO regdao = new RegisterDAO();
boolean result = regdao.insertRecords(rg);
if(result==true)
{
return true;
}
else
{
return false;
}
}
}
/*RegistrationServlet*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Register reg=new Register();
reg.setUser_Fname(request.getParameter("firstname"));
reg.setUser_Lname(request.getParameter("lastname"));
reg.setPassword(request.getParameter("password"));
reg.setConfirm_pass(request.getParameter("confirm_password"));
reg.setContact_no(request.getParameter("mobile"));
reg.setUser_email(request.getParameter("email"));
reg.setUser_address(request.getParameter("address"));
reg.setUser_pincode(request.getParameter("pincode"));
RegisterManager regManager=new RegisterManager();
if(regManager.insertManager(reg)){
// RequestDispatcher requestDispatcher= request.getRequestDispatcher("TCSBLUE.jsp");
// requestDispatcher.forward(request, response);
HttpSession session = request.getSession(true);
session.setAttribute("loginid", reg.getUser_email());
//out.print(session.getAttribute("loginid"));
out.write("Successfully Registered...");
}
else
{
// RequestDispatcher requestDispatcher= request.getRequestDispatcher("Error.jsp");
// requestDispatcher.forward(request, response);
out.write("Something is going wrong....");
}
}
catch(Exception ex)
{
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
out.close();
}
}

Categories