JDBC 的 一个测试代码
package JDBC_TEST;
import java. sql. *;
public class FirstExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver" ;
static final String DB_URL = "jdbc:mysql://localhost:3306/YKenan" ;
static final String USER = "root" ;
static final String PASS = "YKenan" ;
public static void main ( String[ ] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class. forName ( JDBC_DRIVER) ;
System. out. println ( "Connecting to database..." ) ;
conn = DriverManager. getConnection ( DB_URL, USER, PASS) ;
System. out. println ( "Creating statement..." ) ;
stmt = conn. createStatement ( ) ;
String sql;
sql = "SELECT id, first, last, age FROM Employees" ;
rs = stmt. executeQuery ( sql) ;
while ( rs. next ( ) ) {
int id = rs. getInt ( "id" ) ;
int age = rs. getInt ( "age" ) ;
String first = rs. getString ( "first" ) ;
String last = rs. getString ( "last" ) ;
System. out. println ( "ID: " + id + ", Age: " + age + ", First: " + first + ", Last: " + last) ;
}
rs. close ( ) ;
stmt. close ( ) ;
conn. close ( ) ;
} catch ( SQLException se) {
se. printStackTrace ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
} finally {
try {
if ( rs != null)
rs. close ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
try {
if ( stmt != null)
stmt. close ( ) ;
} catch ( SQLException se2) {
}
try {
if ( conn != null)
conn. close ( ) ;
} catch ( SQLException se) {
se. printStackTrace ( ) ;
}
}
}
}