Database - JDBC (Java - SQL) Connecting To A Database: Mydatabase
Database - JDBC (Java - SQL) Connecting To A Database: Mydatabase
sql)
Connecting to a Database
This example uses the JDBC-ODBC bridge to connect to a database called ''mydatabase''.
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e) {
} catch (SQLException e) {
Creating a Table
This example creates a table called ''mytable'' with three columns: COL_A which holds
strings, COL_B which holds integers, and COL_C which holds floating point numbers.
try {
} catch (SQLException e) {
}
Entering a New Row into a Table
This example enters a row containing a string, an integer, and a floating point number
into the table called ''mytable''.
try {
connection.close();
} catch (SQLException e) {
This example retrieves all the rows from a table called ''mytable''. A row in ''mytable''
consists of a string, integer, and floating point number.
try {
ResultSet rs = stmt.executeQuery(
while (rs.next()) {
String s = rs.getString("COL_A");
int i = rs.getInt("COL_B");
float f = rs.getFloat("COL_C");
process(s, i, f);
}
// Get data using colunm numbers.
rs = stmt.executeQuery(
while (rs.next()) {
String s = rs.getString(1);
int i = rs.getInt(2);
float f = rs.getFloat(3);
process(s, i, f);
} catch (SQLException e) {
This example retrieves all rows from a table called ''mytable'' whose column COL_A
equals ``Patrick Chan''. A row in ''mytable'' consists of a string, integer, and floating point
number.
try {
ResultSet rs = stmt.executeQuery(
rs.next();
String s = rs.getString("COL_A");
int i = rs.getInt("COL_B");
float f = rs.getFloat("COL_C");
process(s, i, f);
} catch (SQLException e) {
This example updates a row in a table called ``mytable''. In particular, for all rows whose
column COL_B equals 123, column COL_A is set to ''John Doe''.
try {
connection.close();
} catch (SQLException e) {
A prepared statement should be used in cases where a particular SQL statement is used
frequently. The prepared statement is more expensive to set up but executes faster than a
statement. This example demonstrates a prepared statement for getting all rows from a
table called ''mytable'' whose column COL_A equals ''Patrick Chan''. This example also
demonstrates a prepared statement for updating data in the table. In particular, for all
rows whose column COL_B equals 123, column COL_A is set to ''John Doe''.
try {
int colunm = 1;
stmt = connection.prepareStatement(
colunm = 1;
colunm = 2;
stmt.setInt(colunm, 123);
} catch (SQLException e) {
If an event handler is specific to a component (that is, not shared by other components),
there is no need to declare a class to handle the event. The event handler can be
implemented using an anonymous inner class. This example demonstrates an anonymous
inner class to handle key events for a component.
component.addKeyListener(new KeyAdapter() {
});
implements ActionListener {
You can get the key that was pressed either as a key character (which is a Unicode
character) or as a key code (a special value representing a particular key on the
keyboard).
component.addKeyListener(new MyKeyListener());
if (evt.getKeyChar() == 'a') {
process(evt.getKeyChar());
if (evt.getKeyCode() == KeyEvent.VK_HOME) {
process(evt.getKeyCode());
}
}
component.addMouseListener(
new MyMouseListener());
extends MouseAdapter {
if ((evt.getModifiers() &
InputEvent.BUTTON1_MASK) != 0) {
processLeft(evt.getPoint());
if ((evt.getModifiers() &
InputEvent.BUTTON2_MASK) != 0) {
processMiddle(evt.getPoint());
if ((evt.getModifiers() &
InputEvent.BUTTON3_MASK) != 0) {
processRight(evt.getPoint());
component.addMouseMotionListener(
new MyMouseMotionListener());
extends MouseMotionAdapter {
process(evt.getPoint());
process(evt.getPoint());
component.addMouseListener(
new MyMouseListener());
if (evt.getClickCount() == 3) {
// triple-click
} else if (evt.getClickCount() == 2) {
// double-click
}
component.addFocusListener(
new MyFocusListener());
extends FocusAdapter {
Constructing a Path
On Windows, this example creates the path \blash a\blash b. On Unix, the path would
be /a/b.
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
str = in.readLine();
process(str);
} catch (IOException e) {
try {
new FileReader("infilename"));
String str;
process(str);
in.close();
} catch (IOException e) {
Writing to a File
new FileWriter("outfilename"));
out.write("aString");
out.close();
} catch (IOException e) {
Creating a Directory
(new File("directoryName")).mkdir();
Appending to a File
try {
out.write("aString");
out.close();
} catch (IOException e) {
Deleting a File
(new File("filename")).delete();
Deleting a Directory
(new File("directoryName")).delete();
try {
// Create temp file.
"pattern", ".suffix");
temp.deleteOnExit();
new FileWriter(temp));
out.write("aString");
out.close();
} catch (IOException e) {
try {
RandomAccessFile raf =
// Read a character.
char ch = raf.readChar();
raf.seek(f.length());
raf.writeChars("aString");
raf.close();
} catch (IOException e) {
Serializing an Object
try {
new FileOutputStream("filename.ser"));
out.writeObject(object);
out.close();
} catch (IOException e) {
Deserializing an Object
try {
new FileInputStream("filename.ser"));
in.close();
} catch (ClassNotFoundException e) {
} catch (IOException e) {
Traversing a Directory
process(f);
if (f.isDirectory()) {
try {
"infilename"), "UTF8"));
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
try {
Writer out = new BufferedWriter(
"outfilename"), "UTF8"));
out.write(aString);
out.close();
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
try {
"infilename"), "8859_1"));
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
try {
"outfilename"), "8859_1"));
out.write(aString);
out.close();
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
Networking (java.net)
Creating a URL
try {
// With components.
"http://hostname:80/index.html");
} catch (MalformedURLException e) {
Parsing a URL
try {
try {
new InputStreamReader(url.openStream()));
String str;
process(str);
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
Resolving a Hostname
try {
} catch (IOException e) {
}
try {
} catch (IOException e) {
try {
new InputStreamReader(socket.getInputStream()));
String str;
process(str);
rd.close();
} catch (IOException e) {
try {
BufferedWriter wr = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
wr.write("aString");
wr.flush();
} catch (IOException e) {
Sending a Datagram
try {
socket.send(request);
} catch (SocketException e) {
} catch (IOException e) {
Receiving a Datagram
try {
byte[] inbuf = new byte[256]; // default size
socket.receive(packet);
} catch (SocketException e) {
} catch (IOException e) {
try {
group = InetAddress.getByName(groupName);
msocket.joinGroup(group);
} catch (IOException e) {
msocket.receive(packet);
} catch (IOException e) {
try {
"228.1.2.3");
socket.send(packet);
} catch (SocketException e) {
} catch (IOException e) {
import java.rmi.*;
try {
"//localhost/RObjectServer");
robj.aMethod();
} catch (MalformedURLException e) {
} catch (UnknownHostException e) {
} catch (NotBoundException e) {
} catch (RemoteException e) {
import java.rmi.*;
public interface RObject extends Remote {
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
super();
try {
Naming.rebind("//localhost/RObjectServer", robj);
} catch (MalformedURLException e) {
} catch (UnknownHostException e) {
} catch (RemoteException e) {
try {
robj.primitiveArg(1998);
robj.byValueArg(new Integer(9));
} catch (MalformedURLException e) {
} catch (UnknownHostException e) {
} catch (NotBoundException e) {
} catch (RemoteException e) {
Return values from remote methods must be primitive, serializable, or Remote. This
example demonstrates the declaration and use of all three return types. 1. Define the
remote interface.
import java.rmi.*;
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
super();
return 3000;
try {
Naming.rebind("//localhost/RObjectServer", robj);
} catch (MalformedURLException e) {
} catch (UnknownHostException e) {
} catch (RemoteException e) {
6. Look Up the Remote object, invoke the methods, and receive the return values.
try {
"//localhost/RObjectServer");
int r1 = robj.primitiveRet();
Integer r2 = robj.byValueRet();
} catch (MalformedURLException e) {
} catch (UnknownHostException e) {
} catch (NotBoundException e) {
} catch (RemoteException e) {
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
super();
// a RemoteException
try {
Naming.rebind("//localhost/RObjectServer", robj);
} catch (MalformedURLException e) {
} catch (UnknownHostException e) {
} catch (RemoteException e) {
6. Look up the Remote object, invoke the method, and catch the exception.
try {
"//localhost/RObjectServer");
robj.aMethod();
} catch (MalformedURLException e) {
} catch (UnknownHostException e) {
} catch (NotBoundException e) {
} catch (RemoteException e) {
Strings (java.lang)
Constructing a String
If you are constructing a string with several appends, it may be more efficient to construct
it using a StringBuffer and then convert it to an immutable String object.
// Modify
int index = 1;
buf.insert(index, "abc");
buf.append("def");
// Convert to string
String s = buf.toString();
int start = 1;
int end = 4;
Searching a String
// First occurrence.
// Last occurrence.
index = string.lastIndexOf('i'); // 4
// Not found.
index = string.lastIndexOf('z'); // -1
int s = 0;
int e = 0;
result.append(str.substring(s, e));
result.append(replace);
s = e+pattern.length();
result.append(str.substring(s));
return result.toString();
int i = Integer.parseInt("123");
long l = Long.parseLong("123");
float f = Float.parseFloat("123.4");
double d = Double.parseDouble("123.4e10");
try {
} catch (UnsupportedEncodingException e) {
try {
} catch (UnsupportedEncodingException e) {
return null;
char ch = '\u5639';
Character.UnicodeBlock block =
Character.UnicodeBlock.of(ch);
while (parser.hasMoreTokens()) {
processWord(parser.nextToken());
1. What are the steps involved in establishing a JDBC connection? This action
involves two steps: loading the JDBC driver and making the connection.
2. How can you load the drivers?
Loading the driver or drivers you want to use is very simple and involves just one
line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the
following code will load it:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Your driver documentation will give you the class name to use. For instance, if
the class name is jdbc.DriverXYZ, you would load the driver with the following
line of code:
Class.forName("jdbc.DriverXYZ");
The method getString is invoked on the ResultSet object rs, so getString() will
retrieve (get) the value stored in the column COF_NAME in the current row of rs.
con.setAutoCommit(false);
Once auto-commit mode is disabled, no SQL statements will be committed until
you call the method commit explicitly.
con.setAutoCommit(false);
PreparedStatement updateSales =
con.prepareStatement( "UPDATE COFFEES SET SALES = ?
WHERE COF_NAME LIKE ?");
updateSales.setInt(1, 50); updateSales.setString(2,
"Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal =
con.prepareStatement("UPDATE COFFEES SET TOTAL =
TOTAL + ? WHERE COF_NAME LIKE ?");
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);
12. How do you call a stored procedure from JDBC?
The first step is to create a CallableStatement object. As with Statement an and
PreparedStatement objects, this is done with an open
Connection object. A CallableStatement object contains a call to a stored
procedure.
13. CallableStatement cs = con.prepareCall("{call
SHOW_SUPPLIERS}");
14. ResultSet rs = cs.executeQuery();
15. How do I retrieve warnings?
SQLWarning objects are a subclass of SQLException that deal with database
access warnings. Warnings do not stop the execution of an
application, as exceptions do; they simply alert the user that something did not
happen as planned. A warning can be reported on a
Connection object, a Statement object (including PreparedStatement and
CallableStatement objects), or a ResultSet object. Each of these
classes has a getWarnings method, which you must invoke in order to see the first
warning reported on the calling object:
16. SQLWarning warning = stmt.getWarnings();
17. if (warning != null)
18. {
19. System.out.println("n---Warning---n");
20. while (warning != null)
21. {
22. System.out.println("Message: " +
warning.getMessage());
23. System.out.println("SQLState: " +
warning.getSQLState());
24. System.out.print("Vendor error code: ");
25.
System.out.println(warning.getErrorCode());
26. System.out.println("");
27. warning = warning.getNextWarning();
28. }
29. }
30. How can you move the cursor in scrollable result sets?
One of the new features in the JDBC 2.0 API is the ability to move a result set’s
cursor backward as well as forward. There are also methods that let you move the
cursor to a particular row and check the position of the cursor.
The first argument is one of three constants added to the ResultSet API to indicate
the type of a ResultSet object: TYPE_FORWARD_ONLY,
TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE. The
second argument is one of two ResultSet constants for specifying whether a result
set is read-only or updatable: CONCUR_READ_ONLY and
CONCUR_UPDATABLE. The point to remember here is that if you specify a
type, you must also specify whether it is read-only or updatable. Also, you must
specify the type first, and because both parameters are of type int , the compiler
will not complain if you switch the order. Specifying the constant
TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in
which the cursor moves only forward. If you do not specify any constants for the
type and updatability of a ResultSet object, you will automatically get one that is
TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.