Java Reference
In-Depth Information
23
24
try
25
{
26
Class .forName ( "sun.jdbc.odbc.JdbcOdbcDriver" ) ;
27
}
28
catch ( ClassNotFoundException ex )
29
{
30
throw new ClassNotFoundException ( ex.getMessage () +
31
"\nCannot locate sun.jdbc.odbc.JdbcOdbcDriver" ) ;
32
}
33
34
try
35
{
36
con = DriverManager .getConnection ( url ) ;
37
}
38
catch ( SQLException ex )
39
{
40
throw new SQLException ( ex.getMessage () +
41
"\nCannot open database connection for " +url ) ;
42
}
43
}
44
}
45
46
// Close makes database connection; null reference to connection
47
public void close () throws SQLException , IOException , ClassNotFoundException
48
{
49
con.close () ;
50
con = null ;
51
}
52
53
// Method to serialize object to byte array
54
private byte [] serializeObj ( Object obj ) throws IOException
55
{
56
ByteArrayOutputStream baOStream = new ByteArrayOutputStream () ;
57
ObjectOutputStream objOStream = new ObjectOutputStream ( baOStream ) ;
58
59
objOStream.writeObject ( obj ) ; // object must be Serializable
60
objOStream.flush () ;
61
objOStream.close () ;
62
return baOStream.toByteArray () ; // returns stream as byte array
63
}
64
65
// Method to deserialize bytes from a byte array into an object
66
private Object deserializeObj ( byte [] buf )
67
throws IOException , ClassNotFoundException
68
{
69
Object obj = null ;
70
71
if ( buf != null )
72
{
73
ObjectInputStream objIStream =
74
new ObjectInputStream ( new ByteArrayInputStream ( buf )) ;
75
76
obj = objIStream.readObject () ; //IOException, ClassNotFoundException
77
}
78
return obj;
79
}
80
81
////////////////////////////////////////////////////////////////////////////
82
// Methods for adding a record to a table
83
////////////////////////////////////////////////////////////////////////////
84
// add to the Stocks Table
85
public void addStock ( String stockSymbol, String stockDesc )
86
throws SQLException , IOException , ClassNotFoundException
87
{
88
Statement stmt = con.createStatement () ;
89
stmt.executeUpdate ( "INSERT INTO Stocks VALUES ('"
90
+stockSymbol+ "'"
91
+ ",'" +stockDesc+ "')" ) ;
92
stmt.close () ;
93
}
94
FIGURE 11-36
Search WWH ::




Custom Search