USING JDBC TO QUERY A DATABASE
Let us take an example to understand how to query or modify a database. Consider a
table named as CUSTOMER is created in MS-ACCESS, with fields cust_id, name,
import java.sql.*;
public class JdbcExample1 {
public static void main(String args[]) {
Connection con = null;
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
Connection Conn = DriverManager.getConnection (jdbc:odbc:Access);
Statement Stmt = Conn.createStatement();
// To create a string of SQL.
String sql = "SELECT * FROM CUSTOMERS";
// Next we will attempt to send the SQL command to the database.
// If it works, the database will return to us a set of results that JDBC will
// store in a ResultSet object
try
{
ResultSet results = Stmt.executeQuery(sql);
// We simply go through the ResultSet object one element at a time and print //out the
fields. In this example, we assume that the result set will contain three //fields
fields. In this example, we assume that the result set will contain three //fields
while (results.next())
System.our.println("Field One: " + results.getString(1) + "Field Two: " +
results.getString(2) + "Field Three: " + results.getString(3));
}
}
// If there was a problem sending the SQL, we will get this error.
catch (Exception e)
{
System.out.println("Problem with Sending Query: " + e);
}
finally
{
result.close();
stmt.close();
Conn.close();
}
} // end of main method
} // end of class
Note that if the field is an Integer, you should use the getInt() method in ResultSet
instead of getString().You can use either an ordinal position (as shown in the above
example) which starts from 1 for the first field or name of field to access the values
from the ResultSet like result.getString(“CustomerID”);
instead of getString().You can use either an ordinal position (as shown in the above
example) which starts from 1 for the first field or name of field to access the values
from the ResultSet like result.getString(“CustomerID”);
Compiling JdbcExample1.java
To compile the JdbcExample1.java program to its class file and place it according to
its package statements, open command prompt and cd (change directory) into the
folder containing JdbcExample2.java, then execute this command:
its package statements, open command prompt and cd (change directory) into the
folder containing JdbcExample2.java, then execute this command:
javac -d . JdbcExample2.java
If the program gets compiled successfully then you should get a new Java class under
the current folder with a directory structure JdbcExample2.class in your current
working directory.
the current folder with a directory structure JdbcExample2.class in your current
working directory.
Running JdbcExample1.java
To run and to see the output of this program execute following command from the
command prompt from the same folder where JdbcExample2.java is residing:
command prompt from the same folder where JdbcExample2.java is residing:
No comments:
Post a Comment