Correct Driver for JDBC Derby
Hi all, I'm new to the forum. I didn't plan on jumping right in and asking for help : ( Thanks in advance for any help!
I'm starting my second year of web development in September, and I decided to work on a personal project over the summer.
I have Java experience and a bit of Oracle SQL but have never worked with a JDBC.
Here is my attempt to pull data:
Using Netbeans 7.1, I created a sample database with a few entries of liquor names (no username or password).
The table is called MIXES. Sorry If I omitted any pertinent information here.
I need help choosing and installing the appropriate driver for this jdbc (I think).
Code:
//imports
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class JavaDBTest {
// database URL
static final String DATABASE_URL = "jdbc:derby://localhost:1527/liquor";
// launch the application
public static void main(String[] args) {
// manage the connection
Connection connection = null;
// query statament
Statement statement = null;
//manage the results
ResultSet resultSet = null;
//connect to database and query the database
try {
//establish connection to database
connection = DriverManager.getConnection(DATABASE_URL, "", "");
//create Statement for querying databse
statement = connection.createStatement();
//process query results
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
System.out.println("Liquors in Database:\n");
for (int i=1; i<=numberOfColumns; i++) {
System.out.printf("%-8s\t", metaData.getColumnName(i));
System.out.println();
}// end for
while (resultSet.next()) {
for (int i=1; i<=numberOfColumns; i++) {
System.out.printf("%-8s\t", resultSet.getObject(i));
System.out.println();
} //end for
} // end while
} // end try
catch (SQLException sqlException) {
sqlException.printStackTrace();
} //end catch
//ensure resultSet, statment and connection are closed
finally {
try {
resultSet.close();
statement.close();
connection.close();
} //end try
catch (Exception exception) {
exception.printStackTrace();
} //end catch
}//end finally
}//end Main
}//end Class JavaDBTest
Re: Correct Driver for JDBC Derby
Derby JDBC driver class can be found in the derby.jar file packaged with the database. Before create a connection to the database you'll need to register the driver class class so that it can be picked-up by the DriverManager to create a connection to the database. You can do it with the following snippet:
Code:
...
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
...
Re: Correct Driver for JDBC Derby
If they're using Java 6+ then there's no need to register the driver.
That's all done automagically these days.
Just make sure the jar is on the runtime classpath.