JDBC Tutorial: MIE456 - Information Systems Infrastructure II
JDBC Tutorial: MIE456 - Information Systems Infrastructure II
JDBC Tutorial: MIE456 - Information Systems Infrastructure II
MIE456 -
Information Systems Infrastructure II
Vinod Muthusamy
November 4, 2004
Milestone 2 overview
RMI
ApptController interface given
Write ApptControllerServer (implement ApptController)
Write ApptControllerClient
JDBC
Write ApptRepositoryDB (extend ApptRepository)
Must translate all calls to SQL statements
JDBC Database
calls JDBC
JDBC
JDBC commands
Java app Database
Database
Database
driver
driver
driver
Eclipse JDBC setup
Install driver
Download MySQL JDBC driver from assignment
Web page
Unzip mysql-connector-xxx.jar
Add mysql-connector-xxx.jar to Eclipse project
Project Properties Java Build Path Libraries
Add External JARs
JDBC steps
1. Connect to database
2. Query database (or insert/update/delete)
3. Process results
4. Close connection to database
1. Connect to database
Load JDBC driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
Make connection
Connection conn = DriverManager.getConnection(url);
URL
Format: “jdbc:<subprotocol>:<subname>”
jdbc:mysql://128.100.53.33/GROUPNUMBER?
user=USER&password=PASSWORD
2. Query database
a. Create statement
Statement stmt = conn.createStatement();
stmt object sends SQL commands to database
Methods
executeQuery() for SELECT statements
executeUpdate() for INSERT, UPDATE, DELETE,
statements
users table
userid firstname lastname password type
Bob Bob King cat 0
John John Smith pass 1
Print the users table
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
String userid = rs.getString(1);
String firstname = rs.getString(“firstname”);
String lastname = rs.getString(“lastname”);
String password = rs.getString(4);
int type = rs.getInt(“type”);
System.out.println(userid + ” ” + firstname + ” ”
+ lastname + ” ” + password + ” ” + type);
}
users table
userid firstname lastname password type
Bob Bob King cat 0
John John Smith pass 1
Add a row to the users table
String str =
"INSERT INTO users
VALUES('Bob', 'Bob', 'King',
'cat', 0)”;
users table
userid firstname lastname password type
Bob Bob King cat 0
4. Close connection to
database
Close the ResultSet object
rs.close();