JAVA连接MySQL稍微繁琐,所以先写一个类用来打开或关闭数据库:
public class DBHelper { String driver = "com.mysql.jdbc.Driver"; String url= "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "123456"; public Connection conn; public PreparedStatement pst; public DBHelper(String sql){ try { // 加载驱动程序 Class.forName(driver); // 连续数据库 conn = (Connection) DriverManager.getConnection(url, user, password); if(!conn.isClosed()){ System.out.println("Succeeded connecting to the Database!"); } pst = (PreparedStatement) conn.prepareStatement(sql);//准备执行语句 } catch (Exception e) { e.printStackTrace(); } } public void close() { try { this.conn.close(); this.pst.close(); } catch (Exception e) { e.printStackTrace(); } } }
再写一个JDBCTest.java来执行相关查询操作
public class JDBCTest { public static void main(String[] args){ String sql = "select * from employee";//SQL语句 try{ DBHelper db = new DBHelper(sql);//创建DBHelper对象 ResultSet rs = (ResultSet) db.pst.executeQuery();// 返回结果集 System.out.println("-----------------"); System.out.println("姓名" +"\t"+ "邮箱" +"\t"+ "日期"); System.out.println("-----------------"); while(rs.next()) { //获取结果集中的数据 String uname = rs.getString("name"); String uemail = rs.getString("email"); String uhiredate = rs.getString("hiredate"); // 输出结果 System.out.println(uname +"\t"+ uemail +"\t"+ uhiredate); } rs.close(); db.close();//关闭连接 }catch(SQLException e) { e.printStackTrace(); } } }
原文:http://www.cnblogs.com/liushao/p/6380723.html