package com.llt.demo; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class DBHelper { public static final String url = "jdbc:mysql://127.0.0.1/test"; // jdbc:mysql://host:port/database name public static final String name = "com.mysql.jdbc.Driver"; public static final String user = "root"; // 数据库登录用户 public static final String password = "123456"; public Connection connection = null; public PreparedStatement pst = null; // 数据库登录密码 public DBHelper(String sql) { try { Class.forName(name);// 指定连接类型 connection = DriverManager.getConnection(url, user, password);// 创建连接 pst = connection.prepareStatement(sql);// 执行Sql语句 } catch (Exception e) { e.printStackTrace(); } } public void close() { try { this.connection.close(); this.pst.close(); } catch (Exception e) { } } }
package com.llt.demo; import java.sql.ResultSet; public class test { public static String sql = ""; public static DBHelper db = null; public static ResultSet ret = null; public static void main(String[] args) { // TODO Auto-generated method stub String sql = "select * from book"; db = new DBHelper(sql); try { ret = db.pst.executeQuery(); while (ret.next()) { int id = ret.getInt(1); String name = ret.getString(2); System.out.println("id:" + id + ",name:" + name); } // 使用完后将数据库连接关闭 ret.close(); db.close(); } catch (Exception e) { e.printStackTrace(); } } }
原文:http://www.cnblogs.com/jayden-en/p/7596827.html