JDBC编程流程以及详细代码

  1. 加载驱动
  2. 打开连接
  3. 执行查询
  4. 处理结果
  5. 清理环境
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class JDBCtest {

    public static void main(String[] args) {
        String sql = "SELECT * from tbl_user";
        // 当前的数据库链接;
        Connection connection = null;
        // 用于向数据库发送sql语句
        Statement statement = null;
        // 结果集,封装了从数据库查询的数据
        ResultSet resultSet = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db", "root", "1078966873");
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                System.out.print(resultSet.getInt("id") + " ");
                System.out.print(resultSet.getString("name") + " ");
                System.out.print(resultSet.getString("password") + " ");
                System.out.print(resultSet.getString("email") + " ");
                System.out.println();
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                resultSet.close();
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }

}

posted @ 2017-10-23 11:37  彭于晏码分晏  阅读(406)  评论(0编辑  收藏  举报