JDBC基本操作示例
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- public class TestJDBC {
- public static void main(String[] args) {
- Connection conn = null;
- PreparedStatement pstmt = null;
- ResultSet rs = null;
- try {
- Class.forName("com.mysql.jdbc.Driver");
- conn = DriverManager.getConnection("jdbc:mysql:///test", "root", "root");
- pstmt = conn.prepareStatement("select * from _user");
- rs = pstmt.executeQuery();
- while (rs.next()) {
- System.out.println(rs.getString("username"));
- }
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- if (rs != null) {
- try {
- rs.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- if (pstmt != null) {
- try {
- rs.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- if (conn != null) {
- try {
- rs.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }