Null pointer exception after initialize - java

private static String dbURL = "jdbc:mysql://localhost:3306/mydb";
private static String username = "secret";
private static String password = "secret";
private static Connection conn = null;
public static void initDbConnection(){
try {
conn = DriverManager.getConnection(dbURL, username, password);
Class.forName("com.mysql.jdbc.Driver");
} catch (SQLException e1) {
e1.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void test3(){
initDbConnection();
try{
String sql = "SELECT * FROM Products";
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery(sql);
while (result.next()){
String name = result.getString("name");
System.out.println(name);
}
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
Why I'm getting null pointer exception on conn even though I called the initDbConnection() on test3() ? How will I elimate this problem?

Class.forName("com.mysql.jdbc.Driver");
should be the first line. As this load the mysql driver in the memory. Then you will acquire the connection.
So it should be
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, username, password);
} catch (SQLException e1) {
e1.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}

Related

Fail to retrieve data from postgresql

this is my connection string for connection postgresql database .And using this code I am able to connect the db
connection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5433/Test", "youtube",
"1");
Then I am using the same code to retrieve some data .And I get this exception
org.postgresql.util.PSQLException: ERROR: "userdetail" NOT EXIST
Position: 27
which referr this line
con=GetDbConn();
So mytable name is UserDetail not userdetail I dont understand why am i getting this exception message
And this is my code
public class DbUtils {
private static final String DB_DRIVER="org.postgresql.Driver";
private static final String DB_CONN="jdbc:postgresql://127.0.0.1:5433/Test";
private static final String DB_USER="youtube";
private static final String DB_PASS="1";
public void SelectUserDetails() {
Connection con=null;
Statement statement;
String query="select isim,soyisim from UserDetail";
try {
con=GetDbConn();
statement= con.createStatement();
ResultSet resultSet=statement.executeQuery(query);
while(resultSet.next()){
String isimM=resultSet.getString("isim");
String soyisimM=resultSet.getString("soyisim");
System.out.println("isim :"+soyisimM+" soyisim: "+soyisimM);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static Connection GetDbConn() {
Connection con = null;
try {
Class.forName(DB_DRIVER);
con=DriverManager.getConnection(DB_CONN, DB_USER, DB_PASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
}

Why i can't connect to mysql database in java?

I found this code in a tutorial but it isn't working when I debug it try the connection and then it isn't throw exception only go to the finally block without do any line of code under the DriverManager.getConnection().
Why? Anyone has an idea?
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://host/databasename";
String user = "user";
String password = "pass";
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
con = (Connection) DriverManager.getConnection(url, user, password);
st = (Statement) con.createStatement();
rs = st.executeQuery("SELECT * FROM Message");
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Logcat write this:
Logcat Message
1) DriverManager.getConnection() returns an object of type Connection, so there is no need to cast it. Same thing for st = (Statement) con.createStatement();
2) Unless you're running MySQL on a remote machine, you need to make sure you have MySQL installed on your local machine. If you decide to run MySQL on your local machine, you can connect to it with String url = "jdbc:mysql://localhost/{existing_db_name}"; given that everything else remains the same.
3) It seems like you're catching the same exception twice:
try{
con = (Connection) DriverManager.getConnection(url, user, password);
...
}catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
As a result, your second catch block, the one that prints the exception message to System.err, never runs. Instead, you print the exception message to a Logger. This might be why you think no exception is being thrown, when in reality, an exception is being thrown.
4) Make sure you download the JDBC driver for MySQL. Copy and paste it into the directory of your project.
I've deleted some catch block:
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://host:3306/databasename";
String user = "user";
String password = "pass";
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
con = (Connection) DriverManager.getConnection(url, user, password);
st = (Statement) con.createStatement();
rs = st.executeQuery("SELECT * FROM Message");
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException ex) {
ex.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
Can you please specify what String url are you using? At this point, with these modifications I obviously get a SQLException with No suitable driver found for jdbc:mysql://host/databasename

using combobox selectedItem on a function

i have an function connexion to a database
and i have a code that i have a select and display elements in a combobox
so i want pass on class connexion.java the combobox selectedItem becaue it contains the all of databases that i have
so i want tha classe connexion be dynamic so pass the element selected on this class
i don"t know how can i do that please help me
public class Connexion {
private static Connection conn;
{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex);}
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/mohammedia", "root", "123456");
} catch (SQLException ex) {
Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex); }
}
public static Connection getconx()
{
return conn;
}
}
Use this class
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.NamingException;
import org.apache.commons.dbcp.BasicDataSource;
import sun.jdbc.rowset.CachedRowSet;
public class SQLConnection {
private static Connection con = null;
private static BasicDataSource dataSource;
//we can enable and disable connection pool here
//true means connection pool enabled,false means disabled
private static boolean useConnectionPool = true;
private static int count=0;
private SQLConnection() {
/*
Properties properties = new Properties();
properties.load(new FileInputStream(""));
maxActive = properties.get("maxActive");
*/
}
public static String url = "jdbc:mysql://localhost:3306/schemaname";
public static String password = "moibesoft";
public static String userName = "root";
public static String driverClass = "com.mysql.jdbc.Driver";
public static int maxActive = 20;
public static int maxIdle = 10;
private static final String DB_URL = "driver.classs.name";
private static final String DB_USERNAME = "database.username";
static {
/*Properties properties = new Properties();
try {
properties.load(new FileInputStream("D:\\CollegeBell\\properties\\DatabaseConnection.properties"));
//properties.load(new FileInputStream("E:\\vali\\CollegeBell\\WebContent\\WEB-INF"));
//properties.load(new FileInputStream("D:\\DatabaseConnection.properties"));
url = properties.getProperty(DB_URL);
System.out.println(url);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
dataSource = new BasicDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUsername(userName);
dataSource.setPassword(password);
dataSource.setUrl(url);
dataSource.setMaxActive(maxActive);
dataSource.setMinIdle(maxIdle);
dataSource.setMaxIdle(maxIdle);
}
//public static Connection getConnection(String opendFrom) throws SQLException,
public static Connection getConnection(String openedFrom) {
count++;
System.out.println("nos of connection opened till now="+count);
System.out.println("Connection opended from "+openedFrom);
// System.out.println("Connection Opended ");
try {
if (useConnectionPool) {
con = dataSource.getConnection();
System.out.println(dataSource.getMinEvictableIdleTimeMillis());
//dataSource.setMaxWait(15000);
System.out.println(dataSource.getMaxWait());
System.out.println(count );
} else {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, userName, password);
}
}
//System.out.println("Connection : " + con.toString());
catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
return con;
}
public static void closeConnection(Connection con, String closedFrom)
{
//System.out.println("Connection closed from: " + con.toString());
// System.out.println("Connection closed from: " + closedFrom);
//log.info("Connection closed from: " + closedFrom);
if(con != null){
count--;
System.out.println("Connection count value after closing="+count);
System.out.println("Connection closed from: " + closedFrom);
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//added by nehal
public static void closeStatement(Statement ps, String closedFrom)
{
if(ps != null){
System.out.println("Statement closed from: " + closedFrom);
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void closePreparedStatement(PreparedStatement ps, String closedFrom)
{
if(ps != null){
System.out.println("Statement closed from: " + closedFrom);
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void closeResultSet(ResultSet rs, String closedFrom)
{
if(rs != null){
System.out.println("ResultSet closed from: " + closedFrom);
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//added by nehal
/*public static ResultSet executeQuery(String query) throws Exception {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
CachedRowSet crset = null;
try {
con = getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(query);
crset = new CachedRowSet();
crset.populate(rs);
} catch (Exception e) {
throw e;
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null && !con.isClosed()) {
con.close();
}
}
return crset;
}
public static int executeUpdate(String query) throws Exception {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
int rows = -1;
try {
con = getConnection();
stmt = con.createStatement();
rows = stmt.executeUpdate(query);
} catch (Exception e) {
throw e;
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null && !con.isClosed()) {
con.close();
}
}
return rows;
}
public static boolean execute(String query) throws Exception {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
boolean rowsreturned = false;
try {
con = getConnection();
stmt = con.createStatement();
rowsreturned = stmt.execute(query);
} catch (Exception e) {
throw e;
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null && !con.isClosed()) {
con.close();
}
}
return rowsreturned;
}*/
/*
* public static void closeConnection(Connection con) { try { con.close();
* con=null; } catch (SQLException e) { // TODO Auto-generated catch block
* e.printStackTrace(); } }
*/
}
A JComboBox accepts any kind of object, so you can simply do something like this.
Connection con = new Connection();
JComboBox box = getBox();
box.addItem(con);
And to retreive the value:
JComboBox box = getBox();
Connection con = (Connection)box.getSelectedItem();
However in your Connection class you must override the toString() function, because this is used to display the box.
class Connection
{
public String toString()
{
return "BoxItemDisplayvalue"; <--- here you must put something meaningfull which is displayed in the box.
}
}
So you can instantiate a connection representing the connection that you want, and when the user selects an item from the combobox, you will have the connection it represents.
For what i understand, you have 2 classes..
One the gui where you have a comboBox with the schema name where u want to get connected.
So you have to have a EventListener to "listen" when the submit button is pressed.
For example:
Connection con = null;
JButton submitButton = new JButton("Confirm db");
submitButton.addActionListener(new MyConnectionListener());
..
//Could be inner class
class MyConnectionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent evt){
if(cmb.getSelectedItem() != null){
con = Connection.getConx(cmb.getSelectedItem().toString());
}
}
}
And in your Connexion class
public class Connexion {
public static Connection getconx(String schema)
{
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex);}
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/"+schema, "root", "123456");
} catch (SQLException ex) {
Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex); }
}
return conn;
}
}

can't get connection to database through java class

i'm trying to establish connection with mysql database through file properties and then run the information from servlet. my Connection class looks like this:
public class pageDao {
private Connection connection;
private Statement statement;
private pageDao() {
Properties prop = new Properties();
try {
//Class.forName("oracle.jdbc.driver.OracleDriver");
//Class.forName("org.gjt.mm.mysql.Driver");
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException cnfe) {
System.out.println("Error loading driver: " +cnfe);
}
try {
try {
//load a properties file
prop.load(new FileInputStream("config.properties"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String db = prop.getProperty("database");
String dbuser = prop.getProperty("dbuser");
String dbpassword = prop.getProperty("dbpassword");
connection = DriverManager.getConnection(db,dbuser,dbpassword);
} catch (SQLException e) {
e.printStackTrace();
}
}
private static pageDao thisDao;
public static pageDao gedDao()
{
if(thisDao == null)
thisDao = new pageDao();
return thisDao;
}
public PageData getPage(String id)
{
PageData data = new PageData();
try {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from pages where id='"+id+"'");
if(rs.next())
{
data.setId(rs.getString("id"));
data.setParentid(rs.getString("parentid"));
data.setTitle(rs.getString("title"));
data.setTitle4menu(rs.getString("title4menu"));
data.setKeywords(rs.getString("keywords"));
data.setDescription(rs.getString("description"));
data.setMaintext(rs.getString("maintext"));
}
else
return null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data;
}
when i run it, it doesn't show the mistake that connection wasn't established, but when it gets to the
public PageData getPage(String id) {
PageData data = new PageData();
try {
statement = connection.createStatement();
it throws java.lang.NullPointerException.
can anybody help me out with that?
there is no issue with code.
check your passing parameter ...
check sample
private Connection getConnection() {
try {
String dbUrl = "jdbc:mysql://localhost:3306/projectmining";
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(dbUrl, "root", "admin");
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}

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

Categories