[enter image description here][1]while installing mysql on pc, i got an error message that "port 3306 is currently in use. provide another port"
so i changed the port number to 3305.
now i am trying to connect java project in netbeans ide to mysql, but it ain't working even though i tried with both the port numbers.
enter code here
String pword= password.getText();
String name= tf.getText();
String str= null;
Statement stmt= null;
ResultSet rs= null;
Connection conn=null;
try{
Class.forName("java.sql.Driver");
String pwd= "mysql";
String uid="root";
String url="jdbc:mysql://localhost:3306/project";
try{
conn= (Connection)DriverManager.getConnection(url,uid,pwd);
stmt= conn.createStatement();
String sql= "SELECT * FROM login WHERE name='" + name+ "'";
rs= stmt.executeQuery(sql);
rs.next();
str= rs.getString("password");
if(str.equals(pword))
{
menu m= new menu();
m.setVisible(true);
this.setVisible(false);
}
else
JOptionPane.showMessageDialog(null, "Incorrect username or password!");
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Incorrect username or password!");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Error in Connectivity");
}
I did something like this (for MS SQL server) recently however I don't think you specified the database name
`String url ="jdbc:sqlserver://YourPCname\\instancename;databaseName=yourDBname";`
(note you'd need to change "sqlserver" to "mysql")
Also make sure that your server is running.
Related
I have tried to use another proyect and the connection is succesfull but from this proyect I am only able to connect to localhost mysql. I want it to work only on lan.
I am getting "Access denied for user 'root'#'192.168.1.70' (using password: YES)"
Code sample from not working proyect:
Connection con = null;
Statement st = null;
ResultSet rs = null;
try{ con = (Connection) DriverManager.getConnection("jdbc:mysql://"+home.credentials[0],home.credentials[1],home.credentials[2]);
st = (Statement) con.createStatement();
String s = "SELECT * FROM meta";
rs = st.executeQuery(s);
ResultSetMetaData rsmt = rs.getMetaData();
while(rs.next()){
int meta = rs.getInt("meta");
goal.setText(Integer.toString(meta));
}
}catch(Exception e){}
finally{
try{ st.close();
rs.close();
con.close();
}
catch(Exception e){ JOptionPane.showMessageDialog(null, "InformaciĆ³n no encontrada");
}
}
Code sample from another proyect which connects succesfully
try
{
// create our mysql database connection
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://192.168.1.66:3306/jjeventoscore";
Class.forName(myDriver);
Connection conn = (Connection) DriverManager.getConnection(myUrl, "root", "");
// our SQL SELECT query.
// if you only need a few columns, specify them by name instead of using "*"
String query = "SELECT * FROM client";
// create the java statement
Statement st = (Statement) conn.createStatement();
// execute the query, and get a java resultset
ResultSet rs = st.executeQuery(query);
// iterate through the java resultset
while (rs.next()){
String name = rs.getString("name");
String last = rs.getString("last");
String h_phone = rs.getString("h_phone");
String m_phone = rs.getString("m_phone");
String of_phone = rs.getString("of_phone");
String ex_phone = rs.getString("ex_phone");
String email = rs.getString("email");
String medium = rs.getString("medium");
System.out.println(name+" "+last);
}
st.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
You need to give privileges to the user on that Database and that Table.
With privileges, on your MySQL instance:
USE jjeventoscore;
GRANT ALL ON jjeventoscore.* TO 'root'#'192.168.1.70';
Or maybe try
GRANT ALL ON jjeventoscore.* TO 'root'#'192.168.1.70' IDENTIFIED BY '';
Since it says "Using password: YES"
Also, check the password on MySQL. It should match the parameter in this function
Connection conn = (Connection) DriverManager.getConnection(myUrl, "root", "");
I am using Mysql netbeans . I have created a db table "userdetails_summertrainingproject" . In the login form I have two fileds to fill one is "UUId_JTextField" and other is "Password1_JPasswordField". I want to compare that the password value entered by the user is same as that in db for the particular UUId entered by the user. UUid is unique.
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","");
String query = "SELECT password FROM userdetails_summertrainingproject WHERE UUId=?;";
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1,UUId_JTextField.getText());
ResultSet rs = preparedStatement.executeQuery();
char[] password1 = Password1_JPasswordField.getPassword();
String pass1 = new String(password1);
if(rs.getString(query)==pass1){
JOptionPane.showMessageDialog(null, "Logged in successfully");
}
}
catch(Exception e){
System.out.println("Exception in Login:"+e.getMessage());
}
Above is the code I am using.
The Exception is:
Exception in Login:Column 'SELECT password FROM userdetails_summertrainingproject WHERE UUId=?;' not found.
Try this code, you missed rs.next()
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/mysql", "root", "");
String query = "SELECT password FROM userdetails_summertrainingproject WHERE UUId=?;";
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1, UUId_JTextField.getText());
ResultSet rs = preparedStatement.executeQuery();
char[] password1 = Password1_JPasswordField.getPassword();
String pass1 = Arrays.toString(password1);
rs.next();
if (rs.getString("password").equals(pass1)) {
JOptionPane.showMessageDialog(null, "Logged in successfully");
}
} catch (Exception e) {
e.printStackTrace();
}
I think it is batter to use another method for get connection string. otherwise you have to write bellow code again and again.
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/mysql", "root", "");
EDIT:
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "");
String query = "SELECT UUId FROM userdetails_summertrainingproject;";
PreparedStatement preparedStatement = conn.prepareStatement(query);
ResultSet rs = preparedStatement.executeQuery();
rs.next();
String UUId = rs.getString("UUId");
System.out.println("UUId " + UUId);
} catch (Exception e) {
e.printStackTrace();
}
}
Create a class and add this code. then check this code is working or not.
please make sure port, database name, user and password is correct.
If this is give com.mysql.jdbc.CommunicationsException: Communications link failure. most probably your port is incorrect.
I am use these two libraries.
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","");
String query="SELECT password FROM tryingtable WHERE name=?;";
PreparedStatement prepstmt=conn.prepareStatement(query);
prepstmt.setString(1,jtf.getText());
ResultSet rs=prepstmt.executeQuery();
rs.next();
String result=rs.getString("password");;
char[] pass = jpf.getPassword();
String password1= new String(pass);
if(result.equals(password1))
JOptionPane.showMessageDialog(null, "go!!");
else
JOptionPane.showMessageDialog(null, "no!!");
}
catch(Exception e){
System.out.println("Exception:"+e.getMessage());
e.getStackTrace();
}
when you want to compare password field to textfield use
char[] pass_char = passwordField.getPassword();
String pass_string = new String(pass_char);
Above code will give you your password field value in string form, then
if(pass_string.equals(textfield))
JOptionPane.showMessageDialog("Password match");
else
JOptionPane.showMessageDialog("Password did not match");
Im currently attempting to make a login system in Java and SQL and am currently getting an error.
PreparedStatement s1 = con.prepareStatement("SELECT * FROM dbo.Logins WHERE Username=? AND Password=?");
s1.setString(1,loginUsername);
s1.setString(2, loginPassword.toString());
ResultSet rs = s1.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "User Found");
}
else{
JOptionPane.showMessageDialog(null, "Error");
}
When I run that snippet of code it always displays the else part of the if/else and im not sure why. Thank in advance.
Edit: Yes the DB is populated with users.
Edit2: I changed the function to require two string args.
You can fetch number of rows available in your table for given query and if it is great than 0 it will execute User Found statement.
PreparedStatement s1 = con.prepareStatement("SELECT * FROM dbo.Logins WHERE Username=? AND Password=?");
s1.setString(1,loginUsername);
s1.setString(2, loginPassword.toString());
ResultSet rs = s1.executeQuery();
int rowCount = rs.last() ? rs.getRow() : 0; //Number of rows available in table for query
if(rowCount>0)
JOptionPane.showMessageDialog(null, "User Found");
}
else{
JOptionPane.showMessageDialog(null, "Error");
}
You must try to use while(rs.next()) instead of if(rs.next()).
If that does not work, does your DB (which you have mentioned is populated), contain those particular values of username and password that you are searching for ? If not, that may be the problem.
If that too does not work, you may have closed some objects (eg. s1.close() or con.close() ) where you shouldn't. For further help on that you will need to provide a more detailed flow of what you have done in the whole code.
public void Login(String user, String pass) throws ClassNotFoundException, SQLException{
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
MainWindow mw = new MainWindow();
String userName = "<USERNAME>";
String password = "<PASSWORD>";
String url = "<URL>";
Connection con = DriverManager.getConnection(url, userName, password);
PreparedStatement s1 = con.prepareStatement("SELECT * FROM dbo.Logins WHERE Username=? AND Password=?");
s1.setString(1,user);
s1.setString(2, pass);
ResultSet rs = s1.executeQuery();
//int rowCount = rs.last() ? rs.getRow() : 0; //Number of rows
System.out.println("Name: " + user + "\nPass: " + pass);
if(rs.next())
JOptionPane.showMessageDialog(null, "User Found");
else{
JOptionPane.showMessageDialog(null, "Error");
}
con.close();
I am trying to verify username and password with MySQL. But it's not working. I can't find the problem. Can anybody help me fix it?
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String user = jTextField1.getText();
char[] pass = jPasswordField1.getPassword();
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Statement stat = con.createStatement();
String sql = "Select * from tbl_User Where username='" + user + "' and password='"+pass+"'";
rs = stat.executeQuery(sql);
while (rs.next())
{
if (user.equals(rs.getString("username")))
{
if (pass.equals(rs.getString("password")))
{
JOptionPane.showMessageDialog(null,"Login Successfully");
main.getWindows();
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Password");
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Login");
}
}
stat.close();
con.close();
}
catch (SQLException | HeadlessException e)
{
//e.printStackTrace();
JOptionPane.showMessageDialog(null,"PROBLEM OCCURED !!!! ");
}
catch (ClassNotFoundException ex) {
Logger.getLogger(Users.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
}
Actually I think it is not checking the enteries with username and password in database. am I right?
Firstly, select by username, then hash the user entered password en check if it matches the hashed password in the database. I suggest something like SHA-2
I also suggest you write classes to handle your code, i.e a User class..
You also forgot to close your ResultSet
One more thing, use PreparedStatement
You are checking for password and username match 2 times.
String sql = "Select * from tbl_User Where username='" + user + "' and password='"+pass+"'";
There you already check the password and user, First you shuld check if the password its not stored as MD5 or any other hash type
After that sql you only need to check if its returns any row like #Prabhakaran says
Check code which is written is connecting to database, password is not there in the below code
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Second is check the user and pass variable is getting the value from the action event.
Do like this
Statement stat = con.createStatement();
user = user.toLowerCase();
pass = pass.toLowerCase();
String sql = "Select * from tbl_User Where LOWER(username)='" + user + "' and LOWER(password)='"+pass+"'";
rs = stat.executeQuery(sql);
if(rs.next())
{
JOptionPane.showMessageDialog(null,"Login Successfully");
main.getWindows();
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Login");
}
First things first.
Code will only be used to validate the error. So you must paste the error fired by your program.
Since we don't have enough information to the problem, I will try to help you out.
1- It seems your connection variable missing the "Connection" try this :
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"DATABASENAME"?useTimezone=true&serverTimezone=UTC","USERNAME","PASSWORD");
2 - You already made the if statement to the query in the beginning, so you don't have to start all over again with You can simply type :
if (rs.next()) {
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Password");
} then carry on with the exception part
this is the code :
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Statement stat = con.createStatement();
String sql = "Select * from tbl_User Where username='" + user + "' and password='"+pass+"'";
rs = stat.executeQuery(sql);
if (rs.next())
{
JOptionPane.showMessageDialog(null,"Login Successfully");
main.getWindows();
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Password");
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Login");
}
stat.close();
con.close();
}
catch (SQLException | HeadlessException e)
{
//e.printStackTrace();
JOptionPane.showMessageDialog(null,"PROBLEM OCCURED !!!! ");
}
catch (ClassNotFoundException ex) {
Logger.getLogger(Users.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
}`
when i ll try to connecting mysql using jdbc means its succeessfully connected on localhost.but i replaced localhost by my ip address means itz not connected..y dis error is came..how it is cleared..help me.
dis is my coding:
package com.retrieve;
import java.sql.*;
public class retrieve{
public static void main(String[] args) {
System.out.println("Getting All Rows from a table!");
Connection con = null;
String url = "jdbc:mysql://192.168.1.249:3306/";
String db = "login";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+db, user, pass);
try{
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM login");
System.out.println("username: " + "\t" + "password: ");
while (res.next()) {
String s = res.getString("username");
String s1 = res.getString("password");
System.out.println(s1 + "\t\t" + s);
}
con.close();
}
catch (SQLException s){
System.out.println("SQL code does not execute.");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
The error is:
Getting All Rows from a table!
java.sql.SQLException: Data source rejected establishment of connection, message from server: "Host '192.168.1.249' is not allowed to connect to this MySQL server"
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:650)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1808)
at com.mysql.jdbc.Connection.(Connection.java:452)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at com.retrieve.retrieve.main(retrieve.java:15)
With your MySQL server you need to add permission for your user to be able to access your db from the specified IP
Execute following query from mysql console
GRANT ALL ON YOUR_DB.* TO 'root'#'192.168.1.249';
create user 'login'#'192.168.1.249' on your mysql server.
mysql builds users from 'name' (here - login you specified) and 'host' (address from which user connects to server). You can use '%' char to describe 'all hosts'.
consider reading this section of docs:
http://dev.mysql.com/doc/refman/5.1/en/user-account-management.html
Try to close all the resources like Statment, ResultSet objects etc.Also, as #Jigar mentione, grant permission to the users as well.
Please check your port .If you changed your port number ,you got this error like
"com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure"