There are a few easy step to set up a connection to your database in your java program.
1. establish an odbc data source in windows control panel (may be under Administrative tools).
2. you need to import the java.sql package.
3. you need a connection, so type the following into your database class:
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection("jdbc:odbc:/*your data source name goes here*/");
}
catch (ClassNotFoundException exception)
{
System.err.println("Failed to load JDBC/ODBC driver");
exception.printStackTrace();
System.exit(1);
}
catch (SQLException exception)
{
System.err.println("Unable to connect");
exception.printStackTrace();
System.exit(1);
}
4. Find an SQL tutorial on the web.
5. For each query/update etc create a Statement object using the following code:
try
{
Statement statement = connection.createStatement();
/* now use the remainder of this try block to execute your query. Each database query returns a ResultSet object */
ResultSet resultSet = statement.executeQuery("/*your query string goes here*/");
/* the next() method in ResultSet returns true if there are any more records, like an iterator. Therefore, you know if there are any results or not*/
if (resultSet.next())
{
/* If your query was a 'SELECT * FROM ...etc' then you will get a whole row from the table(s) within the database. if you need to extract a number from that record and you know the column number, then use the following */
int id = resultSet.getInt(1);
/* where 1 corresponds to the first column in the table, and so on. Ifyou want to extract a String, the use the getString() method*/
}
}
catch (SQLException exception)
{
}
That's basically the easiest way to go about it (I think). Best to consult a book for a more in-depth look. Try Java - How to Program, by Deitel and Deitel (available at www.deitel.com). I found this very useful.
Not so ...
Closing either the parent Statement or Connection objects will automatically close the ResultSet.
Best thing to do is follow the first link and learn the basics rather than copy someone elses code without really understanding what's going on.
The Java Tutorial has some good links for starters and you'll save money compared with buying overpriced books.
Hi,
Yup, I agree.
In fact, you can actually download a JDBCTest program that show you code to connect to a database.
If you have your Access ODBC DataSource correctly setup.
Simply run the program to see the code generated for you.
http://developer.java.sun.com/developer/onlineTraining/Database/JDBCShortCourse/jdbc/exercises/JDBCTestConnect/index.html
HM