可能会成为一道面试题:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestJDBC {
public static void main(String[] args) {
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
try {
//两种方式
Class.forName("com.mysql.jdbc.Driver");
//new com.mysql.jdbc.Driver();
//连接数据库
conn = DriverManager
.getConnection("jdbc:mysql://localhost/student?user=root&password=root");
//创建一个Statement实例
stat = conn.createStatement();
//执行一些静态的SQL语句
rs = stat.executeQuery("select * from c");
System.out.println("id - name");
while (rs.next()) {
System.out.print(rs.getInt("id"));
System.out.print(" - ");
System.out.print(rs.getString("name"));
System.out.println();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (null != rs) {
rs.close();
rs = null;
}
if (null != stat) {
stat.close();
stat = null;
}
if (null != conn) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}