Java Programming
How to Use Java DataBase
Connectivities (JDBC)
Incheon Paik
Java
1
Computer Industry Lab.
Contents
Java
Simple SQL
Creating Table
Insert Data
Select Data
Accessing Data Using JDBC
2
Computer Industry Lab.
Simple Database
Design
student
studentID
Name
Email
major
course
registration
call_number
name
teacher
semester
SID
call_num
Java
3
Computer Industry Lab.
Database Table Creation
SQL Statement
CREATE TABLE student (
studentID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
email VARCHAR(45),
major VARCHAR(15)
);
CREATE TABLE course (
call_number INT NOT NULL PRIMARY KEY,
name VARCHAR(25) NOT NULL,
teacher VARCHAR(30),
semester VARCHAR(10) NOT NULL
);
CREATE TABLE registration (
SID INT NOT NULL,
call_num INT NOT NULL,
PRIMARY KEY (SID, call_num)
);
Java
4
Computer Industry Lab.
Database Table Creation (Running Screen)
Java
5
Computer Industry Lab.
Table Structure
Java
6
Computer Industry Lab.
Insert & Select Data
Java
7
Computer Industry Lab.
Select Data
Java
8
Computer Industry Lab.
Use JDBC
import java.sql.*;
import java.io.*;
// This example is running with MySql.
public class MyTest{
public static void main(String[] args){
String url =
"jdbc:mysql://localhost/paikic?useUnicode=true&characterEncoding=EUC_JP";
String query = "select * from course";
Connection myCon = null;
Statement stmt = null;
try{
Class.forName("org.gjt.mm.mysql.Driver");
}catch(ClassNotFoundException e){
System.err.println("Class Load Error");
System.err.println(e.getMessage());
}
try{
System.out.println("Trying to connect...");
myCon = DriverManager.getConnection(url,"root", "sccp2002");
stmt = myCon.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
String col1 = rs.getString(1);
String col2 = rs.getString(2);
String col3 = rs.getString(3);
String col4 = rs.getString(4);
System.out.println(" " + col1 + " : " + col2 + " : " + col3 + " : " +
col4);
}
Java
}
}
rs.close(); stmt.close(); myCon.close();
} catch(SQLException e){
System.out.println("MY" + url+" : ");
System.err.println(e.getMessage()+e.toString());
}
9
Computer Industry Lab.
Use JDBC (Running
Screen)
Java
10
Computer Industry Lab.