Java to mysql jdbc connection problems - java

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

Related

Why is the Google App Engine JDBC connection URL not working?

I am developing a Website with a Registration page. I want to store the user details in the table of the MySQL database on Google App Engine. Following is the JDBC connection URL:-
Connection con = DriverManager.getConnection("jdbc:mysql://google/my_database_name?cloudSqlInstance=my_db_instance&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=My_Username&password=My_Password&useSSL=false", "root", "My_Password");
But this URL isn't working as even after registering, no details are stored in the table of my database. So, do suggest any alternatives. Thank you
The following is the RegistrationServlet code which takes input values from Register.jsp and I want it to store the values into my gcloud db table:-
#WebServlet("/RegistrationServlet")
public class RegistrationServlet extends HttpServlet {
private static final long serialVersionUID = 1 L;
public RegistrationServlet() {
super();
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String first_name = request.getParameter("f1");
String last_name = request.getParameter("l1");
String phone = request.getParameter("p1");
String email = request.getParameter("e1");
String uname = request.getParameter("uname");
String user_dob = request.getParameter("udate");
String password = request.getParameter("pwd");
UserData ud = new UserData();
ud.setFirst_name(first_name);
ud.setLast_name(last_name);
ud.setUname(uname);
ud.setPhone(phone);
ud.setEmail(email);
ud.setUser_dob(user_dob);
ud.setPassword(password);
// validate given input
if (first_name.isEmpty() || last_name.isEmpty() || phone.isEmpty() || email.isEmpty() || password.isEmpty()) {
RequestDispatcher rd = request.getRequestDispatcher("Register.jsp");
out.println("<font color=red>Please fill all the fields</font>");
rd.include(request, response);
} else {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// loads mysql driver
try {
Connection con = DriverManager.getConnection("jdbc:mysql://google/my_database_name?cloudSqlInstance=my_db_instance&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=My_Username&password=My_Password&useSSL=false", "root", "My_Password");
String query = "insert into users values(?,?,?,?,?,?,?)";
PreparedStatement ps = con.prepareStatement(query); //generates sql query
ps.setString(1, first_name);
ps.setString(2, last_name);
ps.setString(3, uname);
ps.setString(4, phone);
ps.setString(5, email);
ps.setString(6, user_dob);
ps.setString(7, password);
ps.executeUpdate();
System.out.println("successfully inserted");
ps.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpSession session = request.getSession();
session.setAttribute("username", first_name);
response.sendRedirect("Success.jsp");
}
}
I've followed the GCP CloudSQL for MySQL connection example and it has worked after deployment. I'll go step by step of the process I did so you can compare and see if there's some configuration step missing on your end.
Used a MySQL 2nd Gen Cloud SQL instance. This instance is in the same project as the Google App Engine I'll deploy the script in
Created a new database in the CloudSQL instance
Ran the command gcloud sql instances describe instance1 to get the instance connection name in the form of <MY-PROJECT>:<REGION>:<INSTANCE-NAME>
Downloaded the GCP Java code samples and got to the Java 8 App Engine standard Cloud SQL example:
git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
cd java-docs-samples/appengine-java8/cloudsql/
Completed the fields <INSTANCE_CONNECTION_NAME>, <user>, <password> and <database> from the POM file with the connection values for my case. This fields will be used by the appengine-web.xml to create the cloudsql property that will be used as the connection URL by the code in CloudSqlServlet.java
Also in the appengine-web.xml, I changed the <service> name to default. There's actually no need to change anything on this file but I chose to change the service due to personal preference
The other required dependencies where already in the downloaded POM
Deployed to GAE with mvn appengine:deploy
This is a minimal example of a working GAE to Cloud SQL connection for MySQL. Try to follow this steps to test if the connection works poperly with the provided code example.

mySQL connection won't work

I just can't connect to mySQL using Eclipse and can't figure out why.
Here is my connection class :
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class ConnexionBDD {
static String url = "jdbc:mysql://localhost:8888/Peoples?autoReconnect=true&useSSL=false";
static String login = "root";
static String password = "";
static Connection connection = null;
static Statement statement = null;
static ResultSet result = null;
static String request = "";
public static void main (String[] args) {
System.out.println("will load driver");
loadingDrive();
System.out.println("will connect");
connection();
}
public static void loadingDrive() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch ( ClassNotFoundException e ) {
e.getMessage();
}
}
public static void connection() {
try
{
connection = (Connection) DriverManager.getConnection(url, login, password);
System.out.println("Connected");
statement = (Statement) connection.createStatement();
result = statement.executeQuery(request);
}
catch ( SQLException e )
{
System.out.println(e.getMessage());
} finally {
if ( result != null ) {
try {
result.close();
} catch ( SQLException ignore ) {
}
}
if ( statement != null ) {
try {
statement.close();
} catch ( SQLException ignore ) {
}
}
if ( connection != null ) {
try {
connection.close();
} catch ( SQLException ignore ) {
}
}
}
}
}
Here is the result in the console :
will load driver
will connect
Could not create connection to database server. Attempted reconnect 3 times. Giving up.
I have the connector (mysql-connector-java-5.1.41-bin.jar) in the file WebContent/WEB-INF/lib.
I installed mySQL on my mac.
I installed MAMP, I can reach phpmyadmin and add a new database, but it's kind of weird though, phpmyadmin is already logged as default and clicking the "Exit" button does not disconnect me I don't know why..
The url of phpmyadmin is :
http://localhost:8888/phpmyadmin/index.php
Why can't I connect to mySQL ?
EDIT :
I changed my url with the right port (8889) after checking out the mySQL port on MAMP, but nothing changed in the output of the console.
MySQL and phpMyAdmin cannot be on the same port.
Are you sure that your MySQL is not running on the default port? 3306
UPDATE:
If you are not already using Maven, please do so. It will aid you in managing your packages. That way you can avoid your method: loadingDrive()
I just ran you code locally with a test database. It runs fine for me.
I did the following changes to your code:
I removed the loadingDrive()
Altered request to static String request = "SELECT 1";. This query string is good for testing if the connection to the database is working properly.
I printed the request to the console:
result = statement.executeQuery(request);
System.out.println(result.next());
I added the mysql jdbc connector to my pom.xml file:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
After this I ran the code and this is the console output:
will connect
Connected
true
I still think your MySQL port is wrong. Do you run MySQL locally? Can you connect to it with phpMyAdmin?
I tried to change the url to contain the wrong port. I then received:
Could not create connection to database server. Attempted reconnect 3 times. Giving up.
So I strongly believe that your port is wrong. Can you try to change your url to the following?
static String url = "jdbc:mysql://localhost:3306/Peoples?autoReconnect=true&useSSL=false";

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

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!

phpMyAdmin and Java Connection

I am trying to connect my java program to a database that i have created using phpmyadmin using a university server. so the database is on the university server. how do i get the connection to the db from the java program? i have tried this code, but it gives me an error message?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Connector {
Connection con;
PreparedStatement stmt;
ResultSet rs;
Connector()
{
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("https://NAMEHIDDEN.soi.city.ac.uk:5454/~kdhy546","root","");
stmt=con.prepareStatement("select * from staff where username=? and password=?");
}
catch (Exception e)
{
System.out.println(e);
}
}
}
I am not too sure even, whether this is the correct url to the database? how do i determine the exact link to the database in phpmyadmin?
phpMyAdmin in not a DBMS, it's an UI. If it's a MySQL database, you must use the MySQL JDBC
I have never used phpMyAdmin, but according to this tutorial you should get the connection string if you navigate to the MySQL Account Maintenance Section.
Another thing I am noticing is that you are missing your password in your connection, so without a password your application will not be able to connect.
Lastly, whenever you post a question on SO regarding some code which yields an error, please make sure you include the error, it helps us help you :).
Use the following code.
This is the java part:
import java.net.*;
public class mc
{
public static void main(String args[])
{
try
{
String username="ankur",password="ankur",fname="Shubhendu",ip="12345",lname="Goswami";
String up= "username=" + username + "&password=" + password + "&fname=" + fname + "&lname=" + lname + "&ip="+ ip;
URL url=new URL("http://127.0.0.1:80/alias1/index.php?"+up);
URLConnection urlc=url.openConnection();
urlc.connect();
BufferedReader br=new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String str;
while((str=br.readLine())!=null)
{
System.out.print(str);
}
br.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
PHP part: Anything you will echo from PHP will be stored in String str in Java code:
<?php
mysql_connect("localhost","root","")or die("unable to connect to server");
mysql_select_db("db_name") or die("Unable to connect to database");
$username=$_GET['username'];
$password=md5($_GET['password']);
$fname=$_GET['fname'];
$lname=$_GET['lname'];
$ip=$_GET['ip'];
if(isset($username) && isset($password) && isset($fname) && isset($lname) && isset($ip))
{
$query="INSERT INTO tablename values('$username','$password','$fname','$lname','$ip')";
$fire=mysql_query($query);
}
?>
Hope it works.
Your URL to the database you created with phpMyAdmin is wrong. It should look something similar to:
jdbc:oracle:thin:#//myhost:1521/orc
I recommend you to have a web search for some good Java tutorials on this subject. :)

Categories