java连接mysql,oracle,sqlServer的几种方式

来源:互联网 发布:什么淘宝店铺名好听 编辑:程序博客网 时间:2024/04/27 15:53

JDBC(Java Database Connectivity)是一个独立于特定数据库管理系统、通用的SQL数据库存取和操作的公共接口(一组API),定义了用来访问数据库的标准Java类库,使用这个类库可以以一种标准的方法、方便地访问数据库资源,接下来我们一起来看连接oracle,mysql,sqlserver数据库的几种方式吧

注意:连接数据库的时候需要添加对应的jar包,附上mysql,oracle,sqlserver的对应的jar包

            点击下载

一、直接通过代码连接

       1)、通过Driver 进行数据库连接


      public static void testDriver() throws SQLException{Driver driver = new com.mysql.jdbc.Driver();String url = "jdbc:mysql://localhost:3306/myjava";//mysql数据库连接地址//String url = "jdbc:oracle:thin:@localhost:1521:orcl"//oracle数据库连接地址//        String url = "jdbc:sqlserver://localhost:1433;DatabaseName= your database"//sqlserver数据库连接地址Properties properties = new Properties();properties.setProperty("user", "root");//连接数据库的用户名properties.setProperty("password", "111");//连接数据库的密码Connection connection = (Connection) driver.connect(url, properties);//获取数据库连接System.out.println(connection.toString());//如果打印有值,则说明连接成功}
       2)、通过DriverManger 进行数据库连接

        /** * 直接使用DriverManager 进行连接 * @return * @throws SQLException */     public static void testDriverManager() throws Exception{//    String url = "jdbc:oracle:thin:@localhost:1521:orcl"//oracle数据库连接地址//    String url = "jdbc:sqlserver://localhost:1433;DatabaseName= your database"//sqlserver数据库连接地址    String url = "jdbc:mysql://localhost:3306/myjava";//mysql数据库连接地址    String user = "root";    String password = "111";    String driverClass = "com.mysql.jdbc.Driver";//mysql对应的driver//    String driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//sqlserver对应的driver//    String driverClass = "oracle.jdbc.driver.OracleDriver";//oracle对应的driver    Class.forName(driverClass);    Connection connection = (Connection) DriverManager.getConnection(url, user, password);//获取数据库连接    System.out.println(connection.toString());//如果打印有值,则说明连接成功}

二、通过配置文件进行连接

       1)、将需要的驱动、数据库连接地址等写在jdbc.properties,代码如下          

#mysqljdbcurl = jdbc:mysql://localhost:3306/myjavauserName = rootpwd = 111driver = com.mysql.jdbc.Driver#oracle#jdbcurl = jdbc:oracle:thin:@localhost:1521:orcl#userName = scott#pwd = orcl#driver = oracle.jdbc.driver.OracleDriver#sqlserver#jdbcurl = jdbc:sqlserver://localhost:1433;DatabaseName= your database#driver = com.microsoft.sqlserver.jdbc.SQLServerDriver#userName = lin#pwd = 111     

        2)、使用InputStream 获取jdbc.properties,并通过Properties 进行加载,获取相应的数据库连接地址、用户名、密码,代码如下

public class JDBCUtil1 {private static String driverClass;private static String userName;private static String passWord;private static String jdbcUrl;static {try {Properties properties = new Properties();InputStream inputStream = JDBCUtil1.class.getClassLoader().getSystemResourceAsStream("jdbc.properties");properties.load(inputStream);userName = properties.getProperty("userName");//用户名passWord = properties.getProperty("pwd");//密码driverClass = properties.getProperty("driver");//数据库驱动jdbcUrl = properties.getProperty("jdbcurl"); //数据库连接地址Class.forName(driverClass);} catch (Exception e1) {e1.printStackTrace();}}public static Connection getConnection() throws SQLException {return DriverManager.getConnection(jdbcUrl, userName, passWord);}/** * 释放连接资源 * @param connection * @param statement * @param resultSet */public static void release(Connection connection , Statement statement ,ResultSet resultSet){if(connection!=null){try {connection.close();} catch (SQLException e) {e.printStackTrace();}}if(statement!=null){try {statement.close();} catch (SQLException e) {e.printStackTrace();}}if(resultSet !=null){try {resultSet.close();} catch (SQLException e) {e.printStackTrace();}}}}

         3)、使用时直接通过如下方式连接即可

        Connection connection = JDBCUtil1.getConnection();        System.out.println(connection.toString());

三、通过数据库连接池进行连接

       注意: 使用数据连接池时需要引入相应的jar包,附上下载地址:

                   点击下载

      数据库连接池的基本思想就是为数据库连接建立一个“缓冲池”。预先在缓冲池中放入一定数量的连接,当需要建立数据库连接时,只需从“缓冲池”中取出一个,使用完毕之后再放回去。      

优点:1、资源重用: 3、新的资源分配手段
2、更快的系统反应速度 4、统一的连接管理,避免数据库连接泄露

    数据库连接池包括了DBCP 和C3p0 两种方式:
开源的:DBCP 数据库连接池 C3P0 数据库连接池
数据库连接池的原理如下:


1)、使用DBCP连接池(使用该方式时需要添加额外两个包:commons-pool.jar 和 commons-collections.jar)
(1)、该方式也可使用建立dbcp.properties,代码如下:
需要注意的是:命名方式必须为url,username,password,driverClassName
#mysqlurl = jdbc:mysql://localhost:3306/myjavausername = rootpassword = 111driverClassName = com.mysql.jdbc.DriverinitialSize(10);maxActive(50);minIdle(5);maxWait(5000);#oracle#url = jdbc:oracle:thin:@localhost:1521:orcl#username = scott#password = orcl#driverClassName = oracle.jdbc.driver.OracleDriver#initialSize(10);#maxActive(50);#minIdle(5);#maxWait(5000);#sqlserver#url = jdbc:sqlserver://localhost:1433;DatabaseName= your database#driverClassName = com.microsoft.sqlserver.jdbc.SQLServerDriver#username = lin#password = 111#initialSize(10);#maxActive(50);#minIdle(5);#maxWait(5000);
(2)、可自定义一个工具类来提供给外部进行连接
           public static Connection getConnection(){ Connection connection = null; try { InputStream inputStream = JDBCUtil2.class.getClassLoader().getResourceAsStream("dbcp.properties"); Properties properties = new Properties(); properties.load(inputStream); DataSource dataSource = BasicDataSourceFactory.createDataSource(properties); connection = dataSource.getConnection();} catch (Exception e) {e.printStackTrace();} return connection;   }
(3)、调用时,可通过如下代码进行调用:
                Connection connection = JDBCUtil2.getConnection();System.out.println(connection.toString());
2)、使用D3P0进行数据库连接池连接
需要注意的是:使用该方式连接是,一般会把数据库相关的数据放置在c3p0-config.xml 进行配置
(1)、新建一个File并命名为c3p0-config.xml,代码如下:
<?xml version="1.0" encoding="UTF-8"?><c3p0-config><named-config name="mysql"><!-- 指定连接数据源的基本属性 --><property name="user">root</property><property name="password">111</property><property name="driverClass">com.mysql.jdbc.Driver</property><property name="jdbcUrl">jdbc:mysql://localhost:3306/myjava</property><!-- 若数据库中连接数不足时, 一次向数据库服务器申请多少个连接 --><property name="acquireIncrement">5</property><!-- 初始化数据库连接池时连接的数量 --><property name="initialPoolSize">10</property><!-- 数据库连接池中的最小的数据库连接数 --><property name="minPoolSize">5</property><!-- 数据库连接池中的最大的数据库连接数 --><property name="maxPoolSize">300</property><!-- C3P0 数据库连接池可以维护的 Statement 的个数 --><property name="maxStatements">20</property><!-- 每个连接同时可以使用的 Statement 对象的个数 --><property name="maxStatementsPerConnection">5</property></named-config><!-- This is my config for oracle --><named-config name="oracle"><property name="driverClass">oracle.jdbc.driver.OracleDriver</property><property name="jdbcUrl">jdbc:oracle:thin:@localhost:1521:orcl</property><property name="user">scott</property><property name="password">orcl</property><property name="initialPoolSize">10</property><property name="maxIdleTime">30</property><property name="maxPoolSize">100</property><property name="minPoolSize">10</property><property name="maxStatements">200</property></named-config></c3p0-config>  

(2)、通过编写一个工具类提供外部进行访问
          public static Connection getConnection(){Connection connection = null;try {DataSource dataSources = new ComboPooledDataSource();connection = dataSources.getConnection();} catch (SQLException e) {e.printStackTrace();}return connection;}
(3)、通过如下代码进行调用:
            Connection connection = JDBCUtil2.getConnection();    System.out.println(connection.toString());
     
0 0