Java Reference
In-Depth Information
The program listed in
Example 18-9
loads a text file format into a relational database. Note
that I
optionally
drop the table before creating it, just in case an older version was in place
(this is
not
the default behavior!). Then the program creates the table and its index. Finally, it
goes into a loop reading the lines from the text file; for each, a prepared statement is used to
insert the user's information into the database.
Example 18-9. TextToJDBC.java
/** Load the database from text file into JDBC relational database.
* Text format is: name:password:fullname:city:prov:country:privs
*/
public
public class
class
TextToJDBC
TextToJDBC
{
protected
protected final
final static
static
String TEXT_NAME
=
"users.txt"
;
protected
protected final
final static
static
String DB_URL
=
"jdbc:idb:userdb.prp"
;
protected
protected static
static
boolean
boolean
dropAndReCreate
=
false
false
;
public
public static
static
void
void
main
(
String
[]
fn
)
throws
throws
Exception
{
BufferedReader is
=
new
new
BufferedReader
(
new
new
FileReader
(
TEXT_NAME
));
// Load the database driver
Class
.
forName
(
"jdbc.idbDriver"
);
System
.
out
.
println
(
"Getting Connection"
);
Connection conn
=
DriverManager
.
getConnection
(
DB_URL
,
"admin"
,
""
);
// user, password
System
.
out
.
println
(
"Creating Statement"
);
Statement stmt
=
conn
.
createStatement
();
System
.
out
.
println
(
"Re-creating table and index"
);
iif
(
dropAndReCreate
)
stmt
.
executeUpdate
(
"DROP TABLE IF EXISTS users"
);
stmt
.
executeUpdate
(
"CREATE TABLE users (\n"
+
"name char(12) PRIMARY KEY,\n"
+
"password char(20),\n"
+
"fullName char(30),\n"
+
"email char(60),\n"
+
"city char(20),\n"
+
"prov char(20),\n"
+
"country char(20),\n"
+
"privs int\n"
+
")"
);
stmt
.
executeUpdate
(
"CREATE INDEX nickIndex ON users (name)"
);