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!
Related
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?
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);
OK so I made a mysql database on godaddy.com
I made an admin table there with 3 fields, ID,Username and Password.
In my program I connected to the database and it shows me the tables so I know its connected(Netbeans)
I downloaded Java JDBC driver and put it in the library of my project.
However when I run the program I get this error:
package testdata;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestData {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try
{
String Name = "rsg";
String Pass= "dfgd";
String Host = "blahhhhhhhhhhhhhhh";
Connection con = DriverManager.getConnection( Host,Name, Pass);
Statement stmt = con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String query="DELETE FROM ADMIN";
stmt.executeUpdate(query);
String sql = "SELECT * FROM ADMIN";
ResultSet rs = stmt.executeQuery(sql);
rs.moveToInsertRow( );
rs.updateInt("ID", 1 );
rs.updateString("Username", "CHRIS");
rs.updateString("Password", "CHRIS");
stmt.close();
rs.close();
}
catch(Exception e)
{
System.out.println("ERROR");
e.printStackTrace();
}
}
}
error is:
java.sql.SQLException: No suitable driver found for ****THIS IS MY HostName****
at java.sql.DriverManager.getConnection(DriverManager.java:604)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at testdata.TestData.main(TestData.java:28)
add mysql conntector jar file in your classpath.
I thing it's an issue with your host address. Check how should it look in MySql documentation
use
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(DatabaseUrl, DataDaseusername, DatabasePass);
example for DatabaseUrl is given below
jdbc:mysql://192.168.100.100/databasename
mysql-connector-java-5.1.22 download from mysql.com
Insure you have add the jar folder in your project.
I believe its is looking for com.mysql.jdbc.Driver
make sure your connection string is correct for an example "jdbc:mysql://remot-example-mysql999.servage.net:3306/databasename?zeroDateTimeBehavior=convertToNull";
Your JDBC connection string is not correct (you cannot simply use the hostname). You need to use a JDBC URL, which for MySQL takes the form:
"jdbc:mysql://<hostname>:<port>/<database>"
Where <port> is optional if your server is running on the default, and is also optional. Change your getConnection method to this:
connection = DriverManager.getConnection(String.format(
"jdbc:mysql://%s:%s/%s", Host, "3306", "YourDBName"),
Name, Pass);
Replace "YourDBName" with the name of the database you are trying to connect to. You also need to have the MySQL driver JAR in your classpath.
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();
}
}
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. :)