zoukankan      html  css  js  c++  java
  • java连接数据库

    首先有mysql-connector-java-5.1.20-bin.jar

    package jdbc;

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;

    public class JDBC_Connection {
    static String drivername="com.mysql.jdbc.Driver";
    static String url="jdbc:mysql://localhost:3306/test";
    static String username="root";
    static String password="root";
    static{
        try {
            Class.forName(drivername);
            System.out.println("创建驱动成功 ");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            
            e.printStackTrace();
        }
        
    }
    public static Connection getConnection(){
        Connection conn=null;
        try{
        conn=(Connection)DriverManager.getConnection(url,username,password);
        System.out.println("连接数据库成功");
        }catch(SQLException e){
            e.printStackTrace();
        }
        return conn;
    }
    public static void free(ResultSet rs,Connection conn,Statement stmt){
        if(rs!=null)
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                System.out.println("关闭ResultSet失败");
                e.printStackTrace();
            }finally{
                try {
                     if(conn!=null)
                    
                        conn.close();
                     System.out.println("关闭成功");
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        System.out.println("关闭Connection失败");
                        e.printStackTrace();
                    }finally{
                        try{
                            if(stmt!=null)
                                stmt.close();
                        }catch(SQLException e){
                            System.out.println("关闭Statement失败");
                            e.printStackTrace();
                        }
                    }
            }
    }
    public static void main(String[] args){
        
        ResultSet rs = null;
        Connection conn = null;
        Statement stmt = null;
        JDBC_Connection.getConnection();
        JDBC_Connection.free(rs, conn, stmt);
        
    }
    }

  • 相关阅读:
    解决Windows 2000无法访问Windows XP共享目录的问题
    手动清除后门程序Iexplores.exe
    超级天使投资网访谈
    中國web2.0現狀與趨勢調查報告
    google AdSense的佣金政策 (GOOGLE 研究 → Google 服务 → Adsense )
    分类信息和搜索引擎
    web 2.0是生产关系:说徐博客赚钱
    赛门铁克联手八笛众和推在线安全服务 狼人:
    2009年六大网络安全威胁:SQL注入攻击位列榜首 狼人:
    网民关注iPhone、Google、微软和安全 狼人:
  • 原文地址:https://www.cnblogs.com/thehappyyouth/p/3092157.html
Copyright © 2011-2022 走看看