static variables in my "Connect to mysql DB class"

I want to make my class assessible everywhere.

I will create an instance of it in the very beginning of main method

and will call it's methods to get data from DB.

I have a problem.

Here is the part of my code:

import TableItem.Item;

import java.sql.*;

import java.util.Vector;

/**Class is used for loading driver to DriverManager*/

publicclass LoadDriver{

privatestatic Connection connection_db=null;

privatestatic Statement statement=null;

privatestatic String drivername="";

privatestatic String UrltoDB="";

privatestatic String user="";

privatestatic String password="";

privatestatic String overrideBADDATE="zeroDateTimeBehavior=convertToNull&";

/**Constructor loads parameters from external config file*/

public LoadDriver(String drivername, String UrltoDB, String user, String password){

this.drivername=drivername;

this.UrltoDB=UrltoDB;

this.user=user;

this.password=password;

}//LoadDriver constructor

/**This method loads driver to DriverManager*/

publicvoid loadDriverToDriverManager(){

try{

Class.forName(drivername).newInstance();

}

catch (Exception ex){

System.out.println("Loadind driver error: "+ex.getMessage());

}

}

/**This method gets new Connection to DB*/

publicstaticvoid setNewConnectionToDB(){

String t=new String();

try{

t=this.UrltoDB+this.overrideBADDATE+"user="+this.user+"&password="+this.password;

this.connection_db = DriverManager.getConnection(t);

}

catch (SQLException ex){

System.out.println("SQLExeption:"+ex.getMessage());

System.out.println("SQLState:"+ex.getSQLState());

System.out.println("VendorError:"+ex.getErrorCode());

}

}

/**this method returns alive connection*/

publicstatic Connection getAliveConnection(){

if(this.connection_db!=null){

return this.connection_db;

}

else{

System.out.println("Connection died!!!!Need to establish new connection");

returnnull;

}

}

I do not understand.

I've declaredconnection, and other variables asstatic

but through compilation, I get an error message.

For example:

LoadDriver.java:40: non-static variable this cannot be referenced from a static context

t=this.UrltoDB+this.overrideBADDATE+"user="+this.user+"&password="+this.password;

]I get such error on each line where I use

privatestatic Connection connection_db=null;

privatestatic Statement statement=null;

privatestatic String drivername="";

privatestatic String UrltoDB="";

privatestatic String user="";

privatestatic String password="";

privatestatic String overrideBADDATE="zeroDateTimeBehavior=convertToNull&";

in static method.

Where did I do a mistake (or mistakes)?

Message was edited by:

Holod

[5977 byte] By [Holoda] at [2007-11-26 21:25:44]
# 1
"this" is not static.
masijade.a at 2007-7-10 3:06:02 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 2

hm...i thought i have to write this to reslolve ambiguity....

thank you.

and can I ask another small question, or I have to make another thread?

The question is:

Can I get somewhere a small example of class, which provides connection to DB?

Maybe my idea to declare methods and variables as static is not good and there exists another way to solve such task?

Message was edited by:

Holod

Holoda at 2007-7-10 3:06:02 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 3
You are going to create an instance of that class to do your database connection? Okay. Then don't make any of its variables static. And don't make any of its methods static either.
DrClapa at 2007-7-10 3:06:02 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 4

Yes, anyway, I have to:

1.Load driver to DriverManager

2. Create a Connection.

I want to have only one instance of the class,

that will keep only one Connection variable.

By this way, I will have only one connection to DB from each client.

(client is a an aplicaion, that I develop)

I think, that is the best way.

So I want to declare methods of the class as static.

Constructor of the class will set values to URL,USER,PASSWORD String variables,

then special method will load driver to DriverManager

And other special static methods will make UPDATE queries, make SELECT queries and so on. And I will use only one Connection.

So If 50 persons use my application, in common 50 connection will be established to DB.

Ofcourse, it is just temporary algorith of DB access...The best way, I think, Is to establish connection for each query and then close it.

But there a lot problems will arise, so I prefer to use described method.

Holoda at 2007-7-10 3:06:02 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 5

A single, persistent Connection is not a bad idea idea for an application, but that does not mean that it has to be static. And a single Connection can host multiple statements, so at the very least, the other parts of the class (the methods, statements, result sets, connection url parameters) definately do not need to be static, and should not be.

masijade.a at 2007-7-10 3:06:02 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 6

> So I want to declare methods of the class as static.

Okay, fine. Declare your variables and methods static. But then you can't use a constructor, because that creates an instance. You should go and read the beginner Java tutorials that explain what static and instance mean.

And I assume this is not for a real application? If it is (and your talk about 50 users suggests it might be) then you shouldn't be doing any of this code yourself. Even if you knew basic Java, you still shouldn't be doing it. Use a connection pool. Other people have written connection pool code that works much better than anything you or I could write.

DrClapa at 2007-7-10 3:06:03 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 7

Oh, yes, I did not provide all code of my class.

Now, I've hided all variables, they are private.

I declare method as static, if this method does query to DB

for example

public static Vector getAllPerson(){

//makes SELECT query to table Person

//and return result of query as vector

return vectorOfResult;

}

Inside this method I use Connection variable and Statement variable to make a query.

or:

public static void updateDB(String tableName, String columnName, String value){

//this method updates specified table with data

}

Other unneccessary methods declared just as public, but I think to hide them at all. I mean declare them as private.

Holoda at 2007-7-10 3:06:03 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 8

Great suggestion.

I can just google.com+ Connection pool, or what?

I dislike to invent wheels and bicycles (it is russian proverb =)))) )

As I know, connection pools are used in web-oriented applications.

When user connects with his browser to server and server gives this user already prepared connection.

(When i was attending courses, our instructor explained us work of connection pool). But is there any possiblbities to use Connection pool in Java SE?

I know what static means.

In SL-275 static is explained.

I want to create instance of the class in the very beginnig of my program (when user launches an application, instance of the class will be created)

So that is why I do not need write:

LoadDriver loaddriver=new LoadDriver(USER,PASSWORD,URL);

I can write:

Vector queryResultVector=LoadDriver.getAllPerson();

//method returns result of query like

//"SELECT * FROM Person"

You see, my Idea is :

1.Create instance of the class

2.Set all neccessary variables inside this class (Connection, Statement e.t.c.)

3.access methods of this class everywhere I need, without creation another instance.

Allneccessary variables have been set, so why I can't do that?

P.S.Taken from SL-275 Book (page 7-4)

Static variable is similiar in some ways to global variable in other languages. The Java programming language does not have global variables, but a static variable is a single variable that is accessible from any instance of the class.

If a static variable is not marked as private, you can access it from outside a class. To do this, you do not need an instance of the class, you can refer to it through the class name.

I hide all variables inside my class, but I access methods of the class withot having an instance of it.

This is my idea.

If it is bad, no problem.

Just tell me, please, how can I solve it better?

Holoda at 2007-7-10 3:06:03 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 9

> Great suggestion.

> I can just google.com+ Connection pool, or

> what?

If you're creating something to "stand alone" then I'd recommend this one:

http://jakarta.apache.org/commons/dbcp/

But googling is a good way to find a suitable one too.

> As I know, connection pools are used in web-oriented

> applications.

Not necessarily. Connection pools are suitable for any code where you are going to open and close a connection multiple times. They're just particularly useful for multi-threaded applications like those running as web applications.

dcmintera at 2007-7-10 3:06:03 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 10

You see, my Idea is :

1.Create instance of the class

2.Set all neccessary variables inside this class (Connection, Statement e.t.c.)

3.access methods of this class everywhere I need, without creation another instance.

All neccessary variables have been set, so why I can't do that?

There's nothing wrong with this in principle. The problem is more to do with things like:

1. What happens if you try to perform several database operations consecutively.

2. What happens if you try to perform several database operations concurrently (on different threads).

What you've written is liable to stop performing well, stop working completely, or behave in strange ways in these circumstances.

While you understand the meaning of something being declared "static" I don't think you've understood the implications of it.

(edit) Read this and have a think about the issues it discusses and how it avoids them:

http://en.wikipedia.org/wiki/Singleton_pattern

dcmintera at 2007-7-10 3:06:03 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 11

<1. What happens if you try to perform several database operations consecutively.

<2. What happens if you try to perform several database operations concurrently (on different threads).

No, I did not think about that. Thank you!

While you understand the meaning of something being declared "static" I don't think you've understood the implications of it.

(edit) Read this and have a think about the issues it discusses and how it avoids them:

http://en.wikipedia.org/wiki/Singleton_pattern

Probably, You are right.

I will read it in few hours.

P.S.

Thanks for connection pool exmplanation and Apache example

Holoda at 2007-7-10 3:06:03 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 12

I have an idea...

Is it good idea to put in static block :

1. Load jdbc driver to DriverManager

2. Create Connection.

Then I will use Connection variable in class methods, declared as static.

As I understood static block executes once, when class is loaded.

Is that good Idea?

I dont' need class instance if I want to interact with DB.

What do you think about that?

Holoda at 2007-7-10 3:06:03 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 13
Since it's basically what I suggested 3 days ago in Reply #3, I think it is a good idea.
DrClapa at 2007-7-10 3:06:03 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 14
I do not pretend that it's my innovation.I just want to check: did I understand your suggestion right or not =)Thank you for your reply
Holoda at 2007-7-10 3:06:03 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...