JDBC connection to mysql problem

B

bruce

I debug, single step, over this statement and get the error

"Connection = >"Connection" is not a known variable in the current
context.<"

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:
3306/mydb", "myuser", "mypw");

"import java.sql.Connection;" is defined, with all my other import
statements..

I'm also getting that error for "Statement" and "ResultSet"

Thanks for the help,,

Bruce
 
J

John B. Matthews

bruce said:
I debug, single step, over this statement and get the error

"Connection = >"Connection" is not a known variable in the current
context.<"

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:
3306/mydb", "myuser", "mypw");

"import java.sql.Connection;" is defined, with all my other import
statements..

I'm also getting that error for "Statement" and "ResultSet"

See also <http://forums.sun.com/thread.jspa?threadID=5271290>

[Please do not quote signatures.]
 
B

bruce

 bruce said:
I debug, single step, over this statement and get the error
"Connection = >"Connection" is not a known variable in the current
context.<"
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:
3306/mydb", "myuser", "mypw");
"import java.sql.Connection;" is defined, with all my other import
statements..
I'm also getting that error for "Statement" and "ResultSet"

See also <http://forums.sun.com/thread.jspa?threadID=5271290>

[Please do not quote signatures.]

I went to the link you posted and couldn't see how that relates to my
problem except it expresses a dislike of debuggers..

What did I miss? I don't understand why I am getting

"Connection = >"Connection" is not a known variable in the current
context.<"

when I run the program. As I noted, I do have "import
java.sql.Connection;" is defined. I would expect that import would
provide the definition I need??

I am also getting an exception error, as I would expect since Java
does not consider "Connection" as a defined variable!

Thanks for the response. I do appreciate the help..

Bruce
 
B

bruce

 bruce said:
I debug, single step, over this statement and get the error
"Connection = >"Connection" is not a known variable in the current
context.<"
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:
3306/mydb", "myuser", "mypw");
"import java.sql.Connection;" is defined, with all my other import
statements..
I'm also getting that error for "Statement" and "ResultSet"

See also <http://forums.sun.com/thread.jspa?threadID=5271290>

[Please do not quote signatures.]

Maybe you were asking for a more complete copy of my code. So, I'm
posting the routine hear:
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt)
{

String str;

String reelNo = txtReelNo.getText().trim();
System.out.println(reelNo);

try {

try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {

Logger.getLogger(Census1930.class.getName()).log(Level.SEVERE, null,
ex);
}


Connection con = DriverManager.getConnection("jdbc:mysql://
localhost:3306/censusrecords", "censusrecords", "password");

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT lastname FROM
data1930");
rs.next();
str = rs.getString("lastname");

} catch (SQLException ex) {

Logger.getLogger(Census1930.class.getName()).log(Level.SEVERE, null,
ex);
}
}
 
J

John B. Matthews

bruce said:
 bruce said:
I debug, single step, over this statement and get the error
"Connection = >"Connection" is not a known variable in the current
context.<"
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:
3306/mydb", "myuser", "mypw");
"import java.sql.Connection;" is defined, with all my other import
statements..
I'm also getting that error for "Statement" and "ResultSet"

See also <http://forums.sun.com/thread.jspa?threadID=5271290>

[Please do not quote signatures.]

I went to the link you posted and couldn't see how that relates to my
problem except it expresses a dislike of debuggers..

What did I miss? I don't understand why I am getting

"Connection = >"Connection" is not a known variable in the current
context.<"

when I run the program. As I noted, I do have "import
java.sql.Connection;" is defined. I would expect that import would
provide the definition I need?

The import declaration makes a named type visible to the compiler. In
the debugger, only a variable that is in scope and initialized may be
examined. "Connection" is the name of a type; your variable "con" is the
name of an instance of Connection. You should be able to examine the
variable "con" in the debugger any time it is in scope, once it is
initialized.

You may find it easier to see the effect if you break _after_ the the
initialization and _before_ the assignment of interest:

Connection con = null;
--> con = DriverManager.getConnection("...");

<http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14
..4.2>
 
B

bruce

 bruce said:
<dd4df2ee-ce08-45b9-ba63-a1f00e51d...@f26g2000vbm.googlegroups.com>,
I debug, single step, over this statement and get the error
"Connection = >"Connection" is not a known variable in the current
context.<"
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:
3306/mydb", "myuser", "mypw");
"import java.sql.Connection;" is defined, with all my other import
statements..
I'm also getting that error for "Statement" and "ResultSet"
See also <http://forums.sun.com/thread.jspa?threadID=5271290>
[Please do not quote signatures.]
I went to the link you posted and couldn't see how that relates to my
problem except it expresses a dislike of debuggers..
What did I miss?  I don't understand why I am getting
   "Connection = >"Connection" is not a known variable in the current
context.<"
when I run the program. As I noted, I do have "import
java.sql.Connection;" is defined. I would expect that import would
provide the definition I need?

The import declaration makes a named type visible to the compiler. In
the debugger, only a variable that is in scope and initialized may be
examined. "Connection" is the name of a type; your variable "con" is the
name of an instance of Connection. You should be able to examine the
variable "con" in the debugger any time it is in scope, once it is
initialized.

You may find it easier to see the effect if you break _after_ the the
initialization and _before_ the assignment of interest:

    Connection con = null;
--> con = DriverManager.getConnection("...");

<http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14
.4.2>
I am also getting an exception error, as I would expect since Java
does not consider "Connection" as a defined variable!
Thanks for the response. I do appreciate the help..

Auggh.. I knew that. I guess I just "Panicked" when I got the
exception. NOW, I'm sure the exception is due to the database being
empty and I didn't try/catch the "str = rs.getString("lastname");"
Anyhow, I'm off to be verify why I was getting the exception.

Thanks for the great feedback...

Bruce
 
B

bruce

<50525154-89fc-463e-9bdf-1b0740b04...@g18g2000vbn.googlegroups.com>,
 bruce said:
<dd4df2ee-ce08-45b9-ba63-a1f00e51d...@f26g2000vbm.googlegroups.com>,
I debug, single step, over this statement and get the error
"Connection = >"Connection" is not a known variable in the current
context.<"
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:
3306/mydb", "myuser", "mypw");
"import java.sql.Connection;" is defined, with all my other import
statements..
I'm also getting that error for "Statement" and "ResultSet"
See also <http://forums.sun.com/thread.jspa?threadID=5271290>
[Please do not quote signatures.]
I went to the link you posted and couldn't see how that relates to my
problem except it expresses a dislike of debuggers..
What did I miss?  I don't understand why I am getting
   "Connection = >"Connection" is not a known variable in the current
context.<"
when I run the program. As I noted, I do have "import
java.sql.Connection;" is defined. I would expect that import would
provide the definition I need?
The import declaration makes a named type visible to the compiler. In
the debugger, only a variable that is in scope and initialized may be
examined. "Connection" is the name of a type; your variable "con" is the
name of an instance of Connection. You should be able to examine the
variable "con" in the debugger any time it is in scope, once it is
initialized.
You may find it easier to see the effect if you break _after_ the the
initialization and _before_ the assignment of interest:
    Connection con = null;
--> con = DriverManager.getConnection("...");

Auggh.. I knew that. I guess I just "Panicked" when I got the
exception. NOW, I'm sure the exception is due to the database being
empty and I didn't try/catch the "str = rs.getString("lastname");"
Anyhow, I'm off to be verify why I was getting the exception.

Thanks for the great feedback...

Bruce

Yup.. That was the problem. As soon as I put some data in the database
the exception went away. Now back to wrap some try/catch'es around my
database access stuff..

Thanks for the help..

Bruce
 
A

Arne Vajhøj

ResultSet rs = stmt.executeQuery("SELECT lastname FROM
data1930");
> rs.next();
> str = rs.getString("lastname");

I would make that:

if(rs.next()) {
str = rs.getString("lastname");
// process str
} else {
// do whatever needs to be done if no records
}

Arne
 
L

Lew

John said:
Connection con = null;
--> con = DriverManager.getConnection("...");

If these two statements are consecutive like this, one should leave off the
initialization to 'null'.
 
L

Lew

bruce said:
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt)
{

String str;

String reelNo = txtReelNo.getText().trim();
System.out.println(reelNo);

try {

try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {

Logger.getLogger(Census1930.class.getName()).log(Level.SEVERE, null,
ex);

You have a logger, yet you use 'System.out.println()', in a GUI program no
less! What's up with that sh#t?
 
L

Lew

bruce said:
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt)
{

String str;

String reelNo = txtReelNo.getText().trim();
System.out.println(reelNo);

try {

try {
Class.forName("com.mysql.jdbc.Driver");

You only need to call 'Class.forName()' on the database driver once in a
program. Read up in the JLS on class initialization.

All the additional 'Class.forName("com.mysql.jdbc.Driver")' calls in your code
are redundant at best.

'Class.forName()' is no longer the "preferred" way to load a DB driver.
Nowadays we're all supposed to dance down the 'DataSource' path. Most of us
still use 'Class.forName()' for certain scenarios anyway. That said, in
contexts like Tomcat where you can set up data sources quite easily, the new
way is a joy.
 
D

Donkey Hottie

'Class.forName()' is no longer the "preferred" way to load a DB driver.
Nowadays we're all supposed to dance down the 'DataSource' path. Most
of us still use 'Class.forName()' for certain scenarios anyway. That
said, in contexts like Tomcat where you can set up data sources quite
easily, the new way is a joy.

That seems to be a desktop app, not a JavaEE app. Are DataSources
available in Java SE too, nowadays?
 
M

Martin Gregorie

That seems to be a desktop app, not a JavaEE app. Are DataSources
available in Java SE too, nowadays?
Yes, in Java 6 SE. However, java.sql.DataSource is simply an interface
that may or may not be implemented by your JDBC provider.

It is not currently supported in PostgresQL 8.4 or 9.0devel: the
documentation for both versions describe Class.forName() and using the
java -Djdbc.drivers=org.postgresql.Driver option as the only ways to load
it.
 
L

Lew

Yes, in Java 6 SE. However, java.sql.DataSource is simply an interface
that may or may not be implemented by your JDBC provider.

It is not currently supported in PostgresQL 8.4 or 9.0devel: the
documentation for both versions describe Class.forName() and using the
java -Djdbc.drivers=org.postgresql.Driver option as the only ways to load
it.

In Java EE environments PG sets up as a data source just fine. I've
done it repeatedly.

Furthermore, examination of the JDBC JAR for PG shows several
'DataSource' classes in their own 'ds' package, e.g.,
'org.postgresql.ds.PGPoolingDataSource'. I think you are mistaken.
 
M

Martin Gregorie

In Java EE environments PG sets up as a data source just fine. I've
done it repeatedly.

Furthermore, examination of the JDBC JAR for PG shows several
'DataSource' classes in their own 'ds' package, e.g.,
'org.postgresql.ds.PGPoolingDataSource'. I think you are mistaken.
I didn't look in the jar files, just at the documentation I listed on the
JDBC web site plus the defects and future enhancements list. There's no
mention of DataSource or DataManager there or in Chapter 3 under 'Loading
the Driver'.

However, I just looked at the contents of postgresql-8.4-701.jdbc3.jar
which I found to contain:
org/postgresql/jdbc2/optional/PoolingDataSource.class
org/postgresql/jdbc2/optional/SimpleDataSource.class

So, time for a test. I removed the Class.forName() and matching
ClassNotFoundException handler from some working code and ran a
regression test. This worked.

It looks to me as though the Postgres JDBC authors simply forgot to
document this, though they do suggest that using the -Djdbc.drivers JVM
option is preferable to using Class.forName().
 
T

Tom Anderson

In Java EE environments PG sets up as a data source just fine. I've
done it repeatedly.

Furthermore, examination of the JDBC JAR for PG shows several
'DataSource' classes in their own 'ds' package, e.g.,
'org.postgresql.ds.PGPoolingDataSource'. I think you are mistaken.

$ jar tf /usr/local/share/java/postgresql-8.4-701.jdbc4.jar | grep -i datasource | sort
org/postgresql/ds/common/BaseDataSource.class
org/postgresql/ds/jdbc23/AbstractJdbc23PoolingDataSource$1.class
org/postgresql/ds/jdbc23/AbstractJdbc23PoolingDataSource.class
org/postgresql/ds/jdbc23/AbstractJdbc23SimpleDataSource.class
org/postgresql/ds/jdbc4/AbstractJdbc4PoolingDataSource.class
org/postgresql/ds/jdbc4/AbstractJdbc4SimpleDataSource.class
org/postgresql/ds/PGConnectionPoolDataSource.class
org/postgresql/ds/PGPoolingDataSource.class
org/postgresql/ds/PGSimpleDataSource.class
org/postgresql/jdbc2/optional/PoolingDataSource.class
org/postgresql/jdbc2/optional/SimpleDataSource.class
org/postgresql/xa/PGXADataSource.class
org/postgresql/xa/PGXADataSourceFactory.class

That jar also contains a

META-INF/services/java.sql.Driver

Which should, i believe, be sufficient for DriverManager to load the
driver without a Class.forName call.

tom
 
M

Martin Gregorie

That jar also contains a

META-INF/services/java.sql.Driver

Which should, i believe, be sufficient for DriverManager to load the
driver without a Class.forName call.
Is it reasonable to assume that any other JDBC driver jar file would be
similar enough to work without needing the Class.forName() call, which is
said not to be harmful even if not needed.

I'm thinking about writing DB-agnostic code in asking this.
 
M

Martin Gregorie

Martin said:
Is it reasonable to assume that any other JDBC driver jar file would be
similar enough to work without needing the Class.forName() call, which
is said not to be harmful even if not needed.

My guess is "no" for "any other JDBC driver [library]", but it is safe
for the major ones. At a minimum, PG, Derby, Oracle and DB2 have
'DataSource' classes and such.

My experience bears out that the 'Class.forName()' approach is, indeed,
harmless. It depends for its success that drivers are required to
register themselves somehow with the JDBC mechanism upon class
initialization. Presumably they get loaded even via the 'DataSource'
mechanisms; you just don't have to explicitly as for class loading and
initialization in that pattern.

As for repeated 'forName()' calls, they're idempotent, so the only costs
are a screwy program structure and redundant method calls.

The former is more serious. If the class-load happens deep in some
unrelated code, and thus likely in more than one place in code, it
complicates maintenance.
I'm thinking about writing DB-agnostic code in asking this.

I don't believe in agnosticism, but I'm tolerant of it.
Thanks for the confirmation.

I'll leave the single Class.forName() invocation where it was -
immediately in front of the only use of DriverManager.getConnection() to
get the Connection.
I /am/ talking about databases!
:)

I'm with you there: DB agnostic code can be a bitch. The programs in
question use fairly simple SQL that's probably portable amongst the major
databases with little or no modification, but MySQL is definitely not one
of them thanks to its use of auto-incrementing columns rather than
sequences: the schema was developed with PostgreSQL, so naturally it uses
sequences to generate unique soft DBKs. No, I'm not keen on them either,
but in this case the natural keys are all very long - at least that's my
excuse and I'm sticking to it.
 
L

Lew

Martin said:
I'll leave the single Class.forName() invocation where it was -
immediately in front of the only use of DriverManager.getConnection() to
get the Connection.

Where you put these things is a matter of lifecycles.

The class lifecycle is a JVM matter. The connection lifecycle is a resource
matter.

The only real requirement is that the driver class load prior to the first use
of the resource. After that it's OCD.

If you only get the connection once in the lifetime of the driver class, then
the class load can be just prior to the connection establishment. Coincidentally.

public class CxnManager
{
static
{
Class.forName( "org.postgresql.Driver" );
}

/** Obtain a connection.
* @return Connection - client must dispose.
*/
public Connection getConnection()
{
// ...
}

/** Disposal service method.
* @param cxn Connection to dispose.
*/
public void dispose( Connection cxn )
{
if ( cxn != null ) try
{
cxn.close();
}
catch( SQLException exc )
{
logger.error( "Disposal: "+ exc.getLocalizedMessage(), exc );
}
}
}
 
T

Tom Anderson

Is it reasonable to assume that any other JDBC driver jar file would be
similar enough to work without needing the Class.forName() call

The spectacle [1] says (my emphasis):

The DriverManager methods getConnection and getDrivers have been enhanced
to support the Java Standard Edition Service Provider mechanism. JDBC 4.0
^^^^^^^^
Drivers must include the file META-INF/services/java.sql.Driver. This
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
file contains the name of the JDBC drivers implementation of
java.sql.Driver. For example, to load the my.sql.Driver class, the
META-INF/services/java.sql.Driver file would contain the entry:

my.sql.Driver

Applications no longer need to explictly load JDBC drivers using
Class.forName(). Existing programs which currently load JDBC drivers
using Class.forName() will continue to work without modification.

If you have a JDBC4 driver, then you don't need to Class.forName it. But
you can if you like.

The interesting question is what databases have JDBC4 drivers. So far, we
know about PostgreSQL. I've just had a look at jTDS, and it doesn't have a
driver file; the website is pretty positive about it being a JDBC 3
driver, so no surprises there. Our infrastructure guy has changed the SSH
port at the office, and i don't know the new one, so i can't check the
Oracle drivers. MySQL connector/J 5.1.13 has a driver file.

tom

[1] http://download.oracle.com/javase/6/docs/api/java/sql/DriverManager.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top