rss· 投稿· 设为首页· 加入收藏· 繁體版
当前位置: 火魔网 » 程序开发 » Java基础

JDBC连接MYSQL并执行查询

import java.sql.*;

public class TestJDBC {

 public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   ResultSet rs = null;
         try {
           //第一步:加载MySQL的JDBC的驱动
             Class.forName("com.mysql.jdbc.Driver"); 
            //取得连接的 url,能访问MySQL数据库的用户名,密码;数据库名
           String url = "jdbc:mysql://localhost:3306/2";
           String user = "root";
           String password = "19870714";
         //第二步:创建与MySQL数据库的连接类的实例
           conn = DriverManager.getConnection(url, user, password);
         //第三步:用conn创建Statement对象类实例 stmt
           stmt = conn.createStatement();
         //第四步:执行查询,用ResultSet类的对象,返回查询的结果
           String sql = "select * from age";
          rs = stmt.executeQuery(sql);
          while(rs.next()){
            System.out.println(rs.getString("id"));      //取得数据库中的数据
            System.out.println(rs.getString("desc"));
                     }
         } catch (ClassNotFoundException e) {  
         //加载JDBC错误,所要用的驱动没有找到
          System.out.println("驱动加载错误");
   }catch (SQLException ex) {      System.err.println("SQLException:"+ex.getMessage());
   }finally {
         try{
          if(rs != null) {
           rs.close();
           rs = null;           if(stmt != null) {
           stmt.close();
           stmt = null;           if(conn != null) {
           conn.close();
           conn = null;          }catch(SQLException e) {
          System.err.println("SQLException:"+e.getMessage());    }
 }

顶一下
(0)
踩一下
(0)