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

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?

Related

Create connection to SQL database using JDBC Driver- SQLException [duplicate]

I am trying to connect to my database by JDBC on localhost. Connecting via windows authentication is no problem, but I want to connect via SQL authentication. Therefore, I created a login and a user corresponding to this login in my database. I can normally log in SSMS:
My connection string for JDBC:
jdbc:sqlserver://localhost:1433;databaseName=TestBazyDanych;user=doszke;password=doszke123
Thrown exception:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'doszke'. ClientConnectionId:b7005fe3-904d-40c5-a89e-af0cb61250d6
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:254)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:258)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:104)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:4772)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:3581)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:81)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:3541)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7240)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2869)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2395)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2042)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1889)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1120)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:700)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:251)
at main.Main.main(Main.java:38)
The username and password are the same, as those used for loging to SSMS.
Here my class code:
package main;
import java.sql.*;
public class Main {
private static ResultSet selectStan(Connection connection) throws SQLException {
String sql_stmt = "SELECT * FROM STAN;";
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(sql_stmt);
System.out.println("Select executed");
return result;
}
public static void main(String[] args) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String userName = "doszke";
String password = "doszke123";
String url = "jdbc:sqlserver://localhost:1433;databaseName=TestBazyDanych;user=doszke;password=doszke123";
try (Connection con = DriverManager.getConnection(url)) {
if(con != null){
System.out.println("connected");
} else {
System.out.println("unable to connect");
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
As Mark Rotteveel pointed out, I was trying to connect to a LocalDB instance with JDBC, which seemed undoable. (ref: here)
However, I installed jTDS and added to my classpath, changed my connection string to
jdbc:jtds:sqlserver://./TestBazyDanych;instance=LOCALDB#EB7165FD;namedPipe=true
create a connection by the use of this connection string, username and password and it worked. The instance pipe number was taken from cmd line via
sqllocaldb i MSSQLLocalDB
There are few things need to check:
Did you create doszke user under the database and SSMS?
Are you able to login with doszke/doszke123 credentials in SSMS?
Please check 1433 port are open or not in your inbound and outbound firewall.
Trying to telnet on localhost 1433. If it's getting failed change below setting:
Go to Configuration tools -> SQL Server Configuration Manager Select SQL Server Network Configuration -> Select protocol in the right side window enable tcp/ip and restart the services in services.

JDBC MySQL - Java unable to connect to database server

I have a local MySQL running on the default port, but for some reason my code can't connect to it. restdb is the database name I'm trying to connect to. I can do queries from Workbench, so I'm pretty positive the database itself is up.
I have a maven project, and the mysql-connector (mysql-connector-java-8.0.11.jar) is in my Maven Dependencies. Is this the wrong place?
Here is my code. It fails at getConnection. In my error log it tells me:
Could not create connection to database server. Attempted reconnect 3 times. Giving up.
private Connection getConnection()
{
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/restdb?autoReconnect=true&useSSL=true";
String username = "root";
String password = "password";
try
{
DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
conn = DriverManager.getConnection(url, username, password);
} catch (Exception e)
{
System.err.println(e.getMessage());
}
return conn;
}
It looks like you don't have SSL setup. Unless this is intentional, remove the 'useSSL=true' part of the URL.

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

Java Database mySQL access denied

So I am trying to connect to my database and display an item from the table.
The error I am getting is: SQL Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Access denied for user 'Bob'#'%' to database 'TEST'
Is this connecting properly, and if so is the error that the credentials are wrong? And if they are wrong how is it connecting? Thank you
try
{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://THISISTHEHOSTNAME";
String username = "Bob";
String password = "password";
Connection connection = DriverManager.getConnection(url, username, password);
Statement stmt = null;
ResultSet rs = null;
//SQL query command
String SQL = "SELECT * FROM TEST";
stmt = connection.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next())
{
System.out.println(rs.getString("ProductName") + " : " + rs.getString("UnitPrice"));
}
}
catch (SQLException e)
{
System.out.println("SQL Exception: "+ e.toString());
}
catch (ClassNotFoundException cE)
{
System.out.println("Class Not Found Exception: "+ cE.toString());
}
You need to grant the proper privileges to the user that is connecting to the mysql db.
The message you are getting is informing you that while your user was able to connect to the database server, it was not allowed to access the database TEST.
Running the following command in the mysql console would grant such access:
GRANT ALL ON TEST.* TO 'BOB'#'%'
This is extremely permissive and you should keep in mind that db users should have the minimal amount of privileges possible and be restricted to the smallest range of hosts.
I used ShowIP Firefox add on and used the IP instead and didn't get any errors but I'm wondering if should return access granted and I'm unable to find an answer at the moment.
Here's a few things to do:
Check to see if your username and password are correct.
Did you add the username to the correct database? (This needs to be done in CPanel SQL)
Did you allow your database to get connection access from your IP address? (This also needs to be done in CPanel SQL)
create a new user in mysql check all global privileges > go to service in netbeans > database > mysql server at localhost > right click connect and fill username password
this work for me
Please try the code below:
import java.sql.*;
public class InsertPrepared {
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306//test","sanjib","");
PreparedStatement stmt=con.prepareStatement("insert into employee values(???)");
stmt.setInt(1,101);
stmt.setString(2,"Sampa");
int i=stmt.executeUpdate();
System.out.println(i+"Records is inserted");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Java Wont connect to database no matter what driver

import java.sql.*;
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String userName = "root";
String password = "password123!";
String url = "jdbc:oracle:thin:#localhost:3306:procomport";
//Class.forName ("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, userName, password);
//Connection connection = DriverManager.getConnection(url , userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
This is my code I have multiple different databases but it wont connect to any of them what's the problem with this? I keep getting the error it cannot connect to the database. Although I can connect to it using other management tools is it a driver issue? How would I be able to tell if I had the drivers necessary?
The code you've provided to connect to the database won't connect to either MySQL nor Oracle as it stands because it's a mish-mash of attempts to connect to both.
For Oracle, the code should look something like:
String userName = "root";
String password = "password123!";
String url = "jdbc:oracle:thin:#localhost:1521:procomport";
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, userName, password);
(assuming you have a user called root on Oracle, and the Oracle SID is procomport). Note in particular the change of port number: MySQL typically uses 3306, Oracle uses 1521.
For MySQL the connection code should look like:
String userName = "root";
String password = "password123!";
String url = "jdbc:mysql://localhost:3306/procomport";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, userName, password);
(assuming your MySQL database is called procomport). Note the different style of connection URL and the driver class name.
The Oracle driver is typically in a JAR file named ojdbc6.jar, and the MySQL in a JAR named something like mysql-connector-java-5.1.18-bin.jar.
Finally, when you write something like
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
you really aren't helping yourself. The exception e will almost certainly contain the reason why your database connection code isn't working, but by deliberately ignoring it you're making it much harder for yourself to figure out what has gone wrong.
To be honest with you, I'd be tempted to declare the main method throws Exception (by adding this to the end of the public static void main... line), and then you can delete your unhelpful catch block. If an exception is thrown and not handled within main, the JVM will print the stack trace for you before it exits.
After your:
System.err.println();
Place a:
e.printStacktrace();
Then you will see real error message. Probably the driver classes are not in the classpath.
Hope this will help you
Uncomment the line Class.forName("oracle.jdbc.driver.OracleDriver");
Make sure you have the Oracle dirver "oracle.jdbc.driver.OracleDriver" in the classpath

Categories