Re: New to java, having trouble connecting to mySQL DB.


2003-08-18 03:05:31 AM
jbuilder10
pnichols wrote:
Quote
Jools wrote:

>
>Hello nice newsgroup,
>
>I'm new to JBuilder and it's the first java IDE I've used, although I've
>been programming database driven apps in other languages (VB, PHP, etc)
>for a few years now.
>
>Anyway, I'm trying to make a "hello world"-ish java app to connect to a
>remote mySQL database, and open a recordset. The following code throws an
>exception and it all goes downhill from there:
>
>try {
>Class.forName("com.mysql.jdbc.Driver").newInstance();
>}
>catch (Exception ex) {
>System.out.println("Exception: " + ex.getMessage());
>}
>
>Unfortunately the output is not very helpful to me:
>
>Exception: com.mysql.jdbc.Driver
>
>Can anyone please give me some pointers as to where I should look for the
>cause of the problem?
>
>Thanks in advance,
>
>Jools.

You have your connection parameters out of sort for one.

First, make sure that you have the mySQL libaries on your JBuilder
classpath. You can put these under the /Jbuilder/lib/ext folder if you
wish.

The following jar files should be there (depending upon which jdk you are
using):

mini-concurrent.jar
mini-j2ee.jar
jdbc2_0-stdext.jar
mysql-connector-java-3.0.7-stable-bin.jar //this is the one I am using
anyway.

Create a Library from the Tools/Configure Library menu. Call it mysql or
whatever you wish. Make sure once you create this library that you add it
to your project. You do this from the Project/Properties Menu and click on
the Required Libaries Tab. Add the new library (aka mysql) to your
project.

Now create a class for the Database Connectivity. Here is a sample below:

public class DBConnection
{
Connection connection;
static DBConnection dbc;

public DBConnection()
{
try
{
createConnection();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}

public static DBConnection getDbConnection()
{
if(dbc==null)
{
dbc= new DBConnection();

}
return dbc;
}

private boolean createConnection() throws Exception
{
boolean result=true; //assume true
try {
Class.forName("com.mysql.Driver");


connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/somedatabase","root","");
}
catch (Exception ex)
{
result=false;
}
return result;
}
public Connection getConnection()
{
return connection;
}
}


This should create a Database Connection for you.

Another Class can be used to test the connection.


public class TestDataBean
{
DBConnection dbc=DBConnection.getDbConnection();


public TestDataBean()
{
}

public String checkConnection()
{
String result=""; //initialize return value
String sql="SELECT * from SomeTable";
try
{
ResultSet rs= dbc.getConnection().
createStatement().execuateQuery(sql);
if(rs.next()) {
{
result=rs.getString("SomeFieldValue");
}



}
catch(Exception ex)
{
ex.printStackTrace();
}
return result;
}


}

That should get you started.