zoukankan      html  css  js  c++  java
  • Java_jdbc 基础笔记之一 数据库连接

    方式一: 
    1、创建一个Driver实现类的对象 
    2、准备连接数据库的基本信息:url,user,password 
    3、调用Driver接口的connect(url,info)获取数据库连接

    * Driver 是一个接口:数据库厂商必须提供实现的接口,能从其中获取数据库的连接。 1.加入mysql驱动
    * 1)解压mysql-connector-java-5.1.7.zip
    * 2)在当前项目下新建lib目录
    * 4)右键bulid-path,add to
    * buildpath 加入到类路径下

    @Test
        public void testDriver() throws SQLException {
            // 1 创建Driver实现类的对象
            Driver driver = new Driver();
            // 2、准备连接数据库的基本信息:url,user,password
            String url = "jdbc:mysql://127.0.0.1:3306/test";
            Properties properties = new Properties();
            properties.put("user", "root");
            properties.put("password", "admin");
            // 3、调用Driver接口的connect(url,properties)获取数据库连接
            Connection conn = driver.connect(url, properties);
            System.out.println(conn);
        }

    方式二: 

    /** 
    * 编写一个通用的方法,在不修改源程序的情况下,可以获取任何数据库的连接 
    * 解决方案:把数据库驱动Driver实现类的全类名、url、user、pasword 放入一个配置文件中, 
    * 通过修改配置文件的方式实现和具体的数据库的解耦 
    * 
    * @throws IOException 
    * @throws ClassNotFoundException 
    * @throws IllegalAccessException 
    * @throws InstantiationException 
    * 
    */
    
    public Connection getConnection() throws Exception {
            String driverClass = null;
            String urljdbc = null;
            String user = null;
            String password = null;
            // 读取类路径下的jdbc.properties文件
            InputStream is = getClass().getClassLoader().getResourceAsStream(
                    "jdbc.properties");
            Properties properties = new Properties();
            properties.load(is);// .....加载进来
            driverClass = properties.getProperty("driver");
            urljdbc = properties.getProperty("urljdbc");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            // 通过反射创建Driver对象
            Driver driver = (Driver) Class.forName(driverClass).newInstance();// 反射!!
            Properties info = new Properties();
            info.put("user", user);
            info.put("password", password);
            // 通过Driver的connect方法获取数据库的连接
            Connection connection = driver.connect(urljdbc, info);
            return connection;
    
        }
    
        @Test
        public void testConnection() throws Exception {
            System.out.println(getConnection());
        }

    转: https://blog.csdn.net/YL1214012127/article/details/48210857

  • 相关阅读:
    HasMap
    SQL Server 2005新特性之使用with关键字解决递归父子关系
    Silverlight4调用本地音频设备并将音频文件上传到服务器
    sql中exists,not exists的用法
    ie中jQuery无法解析xml文件的解决方案
    NeatUpload的安装使用
    C# 中 MSCHART 饼状图显示百分比
    JSON
    silverlight 独立存储
    SharePoint2010 自定义搜索
  • 原文地址:https://www.cnblogs.com/fps2tao/p/12023213.html
Copyright © 2011-2022 走看看