| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
cyjjkz1
10年前发布

JDBC连接数据库

[Java]代码    

package com.ant.util;    import java.sql.Connection;  import java.sql.DriverManager;  import java.sql.PreparedStatement;  import java.sql.ResultSet;  import java.sql.SQLException;  /**   * @author 杨俊宁   *    */  public class Connector {   Connection con;   PreparedStatement pstmt;   ResultSet rs;   private final String user = "root";    private final String password = "jun19931129";   private final String driver = "com.mysql.jdbc.Driver";   private final String url = "jdbc:mysql://localhost:3306/ant?useUnicode=true&characterEncoding=gbk";   /**    * 该方法依次完成加载驱动䀨ߞ接数据库的任务    * @return con    */      public Connection getConnection()     {       Connection con = null;    try {      Class.forName(driver);     //System.out.println(">>>>>>>>>JDBC Driver Manager加载成功);    } catch (ClassNotFoundException e) {     e.printStackTrace();     System.out.println(">>>>>>>>>JDBC Driver Mana");    }        try {      con = DriverManager.getConnection(url, user, password);      //System.out.println(">>>>>>>>>数据库连接成功!");    } catch (SQLException e) {     e.printStackTrace();     System.out.println("数据库连接失败!");    }    return con;   }      /**    * 该方法依次关闭处理查询结果集对象rs、预处理语句对象pstmt、连接数据库对象con    * @return     */      public void closed()   {       try{        if(rs!=null)         rs.close();         System.out.println("对象rs已关闭!");       }catch(SQLException e){         System.out.println("关闭rs对象异常");         e.printStackTrace();       }    try{     if(pstmt!=null)      pstmt.close();      System.out.println("对象pstmt已关闭!");    }catch(SQLException e){     System.out.println("关闭pstm对象失败");     e.printStackTrace();    }    try{     if(con!=null){      System.out.println("对象con已关闭!");      con.close();     }    }catch(SQLException e){     System.out.println("关闭con对象失败");     e.printStackTrace();    }    con=null;   }  }