import java.sql.*; public class jdbc { //JDBC 驱动名及数据库名 URL static final String JDBC_DRIVE = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost:3306/runoob"; static final String USER = "root"; static final String PASS = "root"; public static void main(String[] args) { // TODO Auto-generated method stub Connection conn = null; Statement stmt = null; try{ //注册JDBC驱动 Class.forName("com.mysql.jdbc.Driver"); //打开链接 System.out.println("链接数据库..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); //执行查询 System.out.println("实例化statement对象..."); stmt = conn.createStatement(); String sql; sql = "select id, name, url from websites"; ResultSet rs = stmt.executeQuery(sql); //展开数据集 while(rs.next()){ int id = rs.getInt("id"); String name = rs.getString("name"); String url = rs.getString("url"); //output data System.out.print("id" + id); System.out.print(", name" + name); System.out.print(", url" + url); System.out.print(" "); } rs.close(); stmt.close(); conn.close(); } catch(SQLException se) { //处理JDBC错误 se.printStackTrace(); } catch(Exception e) { //处理Class.forName 错误 e.printStackTrace(); } finally { //关闭资源 try{ if( stmt != null ) stmt.close(); } catch(SQLException se2) { // } /******************************/ try{ if( conn != null ) conn.close(); } catch(SQLException se3) { se3.printStackTrace(); } } System.out.println("完成"); } }
JDBC的一些代码,自己在eclipse跑了一下,代码源自菜鸟教程!