多情只有春庭月,犹为离人照落花。——张泌《寄人》
准备数据库驱动包(比如: MySQL数据库的驱动包)
加载JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver");
建立数据库连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/memo?user=root&password=root&useUnicode=true&characterEncoding=UTF-8"); MySQL数据连接的URL参数格式如下: jdbc:mysql://服务器地址:端口/数据库名?参数名=参数值
创建操作命令(statement)
Statement statement = connection.createStatement();
执行SQL语句
ResultSet resultSet= statement.executeQuery( "select id,group_id,title,content,is_protected, backgroup,is_remind,remind_time,created_time,modify_time from memo_info");
处理结果集
while (resultSet.next()) { int id = resultSet.getInt("id"); String title = resultSet.getString("title"); String content = resultSet.getString("content"); Date createTime = resultSet.getDate("created_time"); System.out.println(String.format("Memo: id=%d, title=%s, content=%s, createTime=%s", id, title, content, createTime.toString())); }
释放资源(关闭结果集,命令,连接)
//关闭结果集 if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } //关闭命令 if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } //关闭连接命令 if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } }