Trouble with connecting to database - java

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

Related

Android studio can't connect to database in Azure sql server

I am using android studio to develop an application and using Azure Sql Server to host my database. The problem is I was able to connect to my database on SQL server but it has an error of Object not found in my database.
I found out that it might be connecting to my master database instead of the database I want it to connect to. Is there any solution to solve the problem?
package com.example.lenovo.testing1;
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.*;
public class ConnectionClass {
String hostName = "haozailai.database.windows.net";
String dbName = "haozailai";
String user = "username";
String password = "password";
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String ConnURL;
Connection conn = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String url = String.format("jdbc:jtds:sqlserver://haozailai.database.windows.net:1433;database=haozailai;user=username;password=password;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
conn = DriverManager.getConnection(url);
}catch (SQLException se)
{
Log.e("error here 1 : ", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error here 2 : ", e.getMessage());
}
catch (Exception e)
{
Log.e("error here 3 : ", e.getMessage());
}
return conn;
}
}
Picture of my database structure
I tried to connect my sqlserver via java jdbc and did not reproduce your issue.
I can connect to my application db successfully.
My test code:
import java.sql.*;
public class Test {
public static final String url = "jdbc:sqlserver://***.database.windows.net:1433;database=***;user=***password=***;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;";
public static final String name = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
public static Connection conn = null;
public static PreparedStatement pst = null;
public static Statement stmt = null;
public static ResultSet rs = null;
public static void main(String[] args) {
try {
String SQL = "select * from dbo.Student";
Class.forName(name);
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString("name"));
}
close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void close() {
try {
conn.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
After some research, I found out it is because of your connect url.
You need to modify your connect url :
jdbc:jtds:sqlserver://haozailai.database.windows.net:1433/<your application db name> ...
You could refer to the pages below for more details.
https://sourceforge.net/p/jtds/discussion/104389/thread/a672d758/
how to connect sql server using JTDS driver in Android
Update answer:
I have made a slight adjustment to your connect URL and can connect to my application database normally.
try {
String SQL = "select * from dbo.Student";
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String url = String.format("jdbc:jtds:sqlserver://***.database.windows.net:1433/<your database name>;user=***;password=***;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString("name"));
}
close();
} catch (Exception e) {
e.printStackTrace();
}
Notice that remove the database=*** and add "/<your database name>" after your host string.
Please refer to the above code and try again.Any concern, please let me know.
Hope it helps you.
I know this answer is waay too late, but I found this video that totally works: https://www.youtube.com/watch?v=WJBs0zKGqH0
The thing is, you have to download a jtds jar, the guy in the video says where you can get it from and also, you need to add "jtds" before "sqlserver" in connection url and edit the way the 'databe' is written in the connection url, like this:
jdbc:jtds:sqlserver://serverName.database.windows.net:portNr:DatabaseName=dbName;user=....

Connect derby DB to Java

I wanted to connect DB to Java application in Intellij.
I set the classpath correctly, so that javac from cmd is working correct.
I have also downloaded all the jar files needed as a libary, but I still get java.sql.SQLException: No suitable driver found for jdbc:derby
What can be the problem?
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch(java.lang.ClassNotFoundException e) {
e.printStackTrace();
}
final String DATABASE_URL = "jdbc:derby:myDB;create=true;user=user;password=pass";
try (
Connection connection = DriverManager.getConnection(DATABASE_URL, "user", "pass");
)
{
// ...
}
catch (SQLException sqlException)
{
sqlException.printStackTrace();
}
}
You can try if org.apache.derby.jdbc.EmbeddedDriver works. And it seems your connection url is wrong.
final String DATABASE_URL = "jdbc:derby://localhost:1527/myDB;create=true;user=user;password=pass";
Connection connection = null;
try{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
connection = DriverManager.getConnection(DATABASE_URL );
}
catch (Exception e)
{
e.printStackTrace();
}

MYSQL connector saying it has connected even with the wrong username?

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.

Returning the Connection from JDBC into a main method of Java?

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

how to install JDBC and how to use it to connect to mysql?

i am trying to install JDBC but i dont know how, when you only have the jar file, i copied it to my java ext folder but it keep giving me an error, can anyone show me how to complete install the driver and use it?
below is the codes that i used
import java.sql.*;
public class Test1
{
public static void main (String[] args)
{
String url = "jdbc:mysql://localhost:3306/sabayafr_sabmah";
String username = "root";
String password = "ma";
Connection connection = null;
try {
System.out.println("Connecting database...");
connection = DriverManager.getConnection(url, username, password);
System.out.println("Database connected!");
} catch (SQLException e) {
System.err.println("Cannot connect the database!");
e.printStackTrace();
} finally {
System.out.println("Closing the connection.");
if (connection != null) {
try {
connection.close();
} catch (SQLException ignore) {
}
}
}
}
}
And below is the Response that i get
Cannot connect to database server
Update # 3
C:\Users\AlAsad\Desktop>java -cp .;mysql-connector-java-5.0.8-bin.jar Test1
Connecting database...
Cannot connect the database!
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/
sabayafr_sabmah
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Test1.main(Test1.java:12)
Closing the connection.
You're trying to connect MySQL with the URL of a jTDS JDBC driver which is designed specifically for Microsoft SQL Server. This ain't ever going to work. Even not when you fix the current problem by placing the JAR file in classpath.
You really need the MySQL JDBC driver. Also see this answer for a short but complete tutorial
On the other hand, if you are using an IDE such as Netbeans or Eclipse you can add the jar file as a resource to the project.
You certainly have JDBC problems, but the exception isn't telling you that. Read it again:
Exception in thread "main" java.lang.NoClassDefFoundError: Test1
Caused by: java.lang.ClassNotFoundException: Test1
It's your Test1.class that it can't find, not the JDBC driver.
You should not be copying anything into the jre/lib/ext directory. That's for library extensions, not JDBC JARs. It wasn't meant as a crutch for people who don't understand how CLASSPATH works.
I'd write it more like the following. Those close methods will come in handy.
When I run it on my machine, adding the MySQL JDBC JAR to my CLASSPATH, I get the following result:
C:\java -classpath .\mysql-connector-java-5.1.6-bin.jar; persistence.utils.DatabaseUtils
product: MySQL
version: 5.1.24-rc-community
major : 5
minor : 1
Here is the source code:
package persistence.utils;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseUtils
{
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/contacts";
public static final String USERNAME = "contacts";
public static final String PASSWORD = "contacts";
public static void main(String[] args)
{
Connection connection = null;
try
{
String driver = ((args.length > 0) ? args[0] : DRIVER);
String url = ((args.length > 1) ? args[1] : URL);
String username = ((args.length > 2) ? args[2] : USERNAME);
String password = ((args.length > 3) ? args[3] : PASSWORD);
connection = getConnection(driver, url, username, password);
DatabaseMetaData metaData = connection.getMetaData();
System.out.println("product: " + metaData.getDatabaseProductName());
System.out.println("version: " + metaData.getDatabaseProductVersion());
System.out.println("major : " + metaData.getDatabaseMajorVersion());
System.out.println("minor : " + metaData.getDatabaseMinorVersion());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
close(connection);
}
}
public static Connection getConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException
{
Connection connection = null;
Class.forName(driver);
connection = DriverManager.getConnection(url, username, password);
return connection;
}
public static void close(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(Statement statement)
{
try
{
if (statement != null)
{
statement.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(ResultSet resultSet)
{
try
{
if (resultSet != null)
{
resultSet.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void rollback(Connection connection)
{
try
{
if (connection != null)
{
connection.rollback();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
'I am trying to install JDBC'
You don't have to install JDBC. It is part of the JDK & JRE.
Try putting your .jar file in the classpath.
The library that contains the Driver (net.sourceforge.jtds.jdbc.Driver) needs to be on the classpath.
Assuming you start your application with
java Test1
then simply do
java -cp .;driver.jar Test1
where 'driver.jar' should be exchanged with the filename (relative or full path) of your database driver lib.
EDIT
A classpath tutorial will exceed the comments section below this question. Please take a cup of coffee and look at this page. It will most likely help you to continue.

Categories