I am building a database connection scanner for my security course at university. I have used DriverManager.getConnection(connectionURL, username, password) and it seems to work fine but with one exception that I just cannot understand. If I enter the wrong username it is still returning a connection??? my test code is pasted below. Any pointers would be much appreciated. It returns the correct error if I put the wrong password in, if I turn the server off it tells me. But for some unknown reason it will not tell me if the username is wrong, its as if its not even checking!
public class DBConnector {
Connection connection = null;
String dbURL = "jdbc:mysql://localhost:3306";
String userName;
String password;
public DBConnector() {
// TODO Auto-generated constructor stub
}
public Connection tryConnection(String username, String password){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(dbURL, username, password);
System.out.println("Connected");
} catch (InstantiationException e) {
System.out.println("No Connection");
e.printStackTrace();
} catch (IllegalAccessException e) {
System.out.println("Connection Refused");
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
System.out.println("Sql Ex");
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
}
And here is my main class to run the method.
public class MainTest {
public static void main(String[] args) {
DBConnector dbc = new DBConnector();
dbc.tryConnection("", "");
}
}
Maybe this has something to do with running the test on "Localhost"?
Thanks very much!
I would guess that you are logging in as an anonymous user.
You can make your local MySQL Server installation more secure (and hence force your code above to throw an error) by removing the anonymous user like this:
DELETE FROM mysql.user WHERE user='';
FLUSH PRIVILEGES;
Then try connecting with no username and password.
Related
I try to connect to db2 from java, here is my code:
public class Db2Connection {
public static void main(String[] args) {
String jdbcClassName="com.ibm.db2.jcc.DB2Driver";
String url="jdbc:db2://localhost:50001/TEST";
String user="user1";
String password="pass";
System.out.println("before try-catch");
Connection connection = null;
try {
System.out.println("try");
//Load class into memory
Class.forName(jdbcClassName);
//Establish connection
System.out.println("before conn");
connection = DriverManager.getConnection(url, user, password);
System.out.println("after conn");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(connection!=null){
System.out.println("Connected successfully.");
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
To be clear, I add db2jcc.jar to my project and run code with valid url. Program cannot jump over line:
connection = DriverManager.getConnection(url, user, password);
I receive no errors or exception, application just not execute. I have no idea how deal with it, can anyone help me?
Try, after removing colon like :
String url="jdbc:db2//localhost:50001/TEST";
i just wanna ask you about what's wrong about my code..
Here's my code..
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnsubmit){
String Id= String.format("U%03d", countData);
String query="INSERT INTO MsUser(UserID, Username, UserPass, UserFullName, UserEmail, UserPhone, UserAddress, UserGender, Role) VALUES('"+Id+"','"+txtuser.getText()+"','"+txtpass.getText()+"','"+txtname.getText()+"','"+txtemail.getText()+"','"+txtphone.getText()+"','"+txtadd.getText()+"')";
con.executeUpdate(query);
countData=1;
}else{
System.exit(0);
}
and I want if i press submit button, the registration form input to my database.. What should I do? I already had Connect class too..
Here's my connect class code..
public ResultSet executeQuery(String query) {
try {
rs = st.executeQuery(query);
rsm = rs.getMetaData();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Error Connection RS");
}
return rs;
}
public void executeUpdate(String query){
try {
st.executeUpdate(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
My database use .mdb, in it has UserID, Username, UserPass, UserFullName, UserEmail, UserPhone, UserAddress, UserGender, Role in MsUser Table..
Is it something missing? I'm sorry about my bad english, I wish u guys can understand what I mean..
I've trouble with connection to database MySQL. I wrote a console project with databese and I had a class ConnectionManager here. Now I'm starting writing site. I want connect database ang just copy my working classConnectionManager into new dynamic project. But this class return NULL instead of connection. Maybe you know where is problem.
Thank you in advance!
Connector is added. NullPointer exception was called by Connection conn = ConnectionManager.getConnection();
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionManager {
private static String jdbcUrl = "jdbc:mysql://localhost:3306/registration";
private static String user = "root";
private static String password = "root";
private static Connection connection = null;
public static Connection getConnection()
{
if (connection == null)
{
initializeConnection();
}
return connection;
}
private static void initializeConnection()
{
Connection conn;
try {
conn = DriverManager.getConnection(jdbcUrl,user,password);
connection = conn;// doesn't execute and I don't know why
} catch (SQLException e) {
e.printStackTrace();
}
}}
Using: Connection conn = ConnectionManager.getConnection();
Try making the constructor and add your code in that. I'm doing exact same thing and its working. Like this:-
public Connection() {
// TODO Auto-generated constructor stub
try {
if (connection == null)
{
initializeConnection();
}
return connection;
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Probably more than one reason
1- check your user permission
GRANT [type of permission] ON [database name].[table name] TO ‘[username]’#'localhost’;
GRANT ALL PRIVILEGES ON * . * TO 'root'#'localhost';
2- check your jdbc url and its port. Make sure 3306 port is avaible to using mysql
jdbc:mysql://localhost:3306/registration
3- check your jar file
Download .jar file(mysql-connector-java-5.1.37-bin.jar) and move it to libs folder
Right click your project > properties > Libraries > ADD jar/Folder Select your jar file in that folder.
Test your connection
String dbUrl= "jdbc:mysql://localhost:3306/javabase";
String username = "root";
String password = "root";
try (Connection connection = DriverManager.getConnection(dbUrl, username, password)) {
System.out.println("Connected to DB!");
} catch (SQLException e) {
throw new IllegalStateException("Error: ", e);
}
4- check your user password.
if you not sure change your password.
SET PASSWORD FOR 'root'#'localhost' = PASSWORD('root');
I am getting the "java.sql.SQLException: [SQLITE_MISUSE] Library used incorrectly (out of memory)". I paste the code sample for my database connection object
public class DBhandler {
private String DBUrl="d:\\sqlitedb\\somdb.db";
private String driverName="org.sqlite.JDBC";
private String jdbc="jdbc:sqlite:";
private Connection con=null;
private Statement stmnt=null;
public DBhandler()
{
try {
Class.forName(this.driverName);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
this.con=DriverManager.getConnection(this.jdbc+this.DBUrl);
this.stmnt=con.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public CurrentActiveSom getCurrentActiveSom()
{
CurrentActiveSom cas=null;
String query="select * from current_active_som where active=1";
ResultSet rs=null;
try {
rs=this.stmnt.executeQuery(query);
if (rs.next())
{
cas= new CurrentActiveSom();
cas.setMonth(rs.getString("month"));
cas.setYear(rs.getString("year"));
cas.setIsActive(rs.getInt("active"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
rs.close();
this.stmnt.close();
this.con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return cas;
}
public CurrentActiveSom getIsDoneSom(String month,String year)
{
CurrentActiveSom cas=null;
String query="select * from current_active_som where month='"+month+"' and year='"+year+"' and active=0";
ResultSet rs=null;
try {
rs=this.stmnt.executeQuery(query); //this is exception line
}
if (rs.next())
{
cas= new CurrentActiveSom();
cas.setMonth(rs.getString("month"));
cas.setYear(rs.getString("year"));
cas.setIsActive(rs.getInt("active"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
//rs.close(); //if i uncomment this gets null pointer exception
this.stmnt.close();
this.con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return cas;
}
The call to these Two methods with same object of DBhandler like
DBhandler db=new DBhandler();
CurrentActiveSom cas1=db.getCurrentActiveSom();
CurrentActiveSom cas2=db.getIsDoneSom(String month,String year)
then I am getting the above exception ,
but if we call thses 2 methods with different object DBhandler like
DBhandler db1=new DBhandler();
DBhandler db2=new DBhandler();
CurrentActiveSom cas1=db1.getCurrentActiveSom();
CurrentActiveSom cas2=db2.getIsDoneSom(String month,String year)
Then code is working fine.
Is this because of sync problem, with connection ? how to resolve this problem?
Well, the "out of memory"error looks weird, but one definitive error lies in creating Connection once per program run (in the constructor) and then closing it in each data access method.
This code:
CurrentActiveSom cas1=db.getCurrentActiveSom();
closes the Connection, so this code:
CurrentActiveSom cas2=db.getIsDoneSom(String month,String year)
tries to get data from a closed database. This is OK if you are using some kind of connection pooling in which closing a connection returns it to the pool. But it seems you're working on a single physical connection.
So just close it after you're done getting data from DB, and not in each data access method.
You close connection before you call `rs.next()so ResultSet try to read from connection, that has been already closed.
Is it possible to return the type Connection?
And use it as a method passed by reference through out the program?
I find it makes the database interaction a lot easier if it is passed as a method.
public static Connection database(String database, String username, String password) {
String url = "jdbc:postgresql:" + database;
//LOAD DRIVER
try {
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
//CONNECT TO DATABASE
try {
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
db = database("java_jdbc", "admin", "fake_password_1234");
}
You can do that.
Just remember to invoke close() on the connection to release its resources when done.
package mySystem;
import java.sql.*;
import javax.swing.*;
public class MySqlConnector {
Connection conn = null;
public static Connection ConnectDB() {
try {
Class.forName("com.mysql.jdbc.Driver"); //register jdbc driver
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/inventory_db", "root", "");
// JOptionPane.showMessageDialog(null, "Connected to db");
return conn;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}