Java教程

java JDBC连接sqlServer、MySQL、Oracle、Access数据库

本文主要是介绍java JDBC连接sqlServer、MySQL、Oracle、Access数据库,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一、连接sqlServer

        1、Sql Server验证(用户名/密码方式连接)

public static Connection getConnectionForSqlServer() throws ClassNotFoundException, SQLException{
        Connection conn = null;
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        conn = DriverManager.getConnection("jdbc:sqlserver://192.168.10.1:1433; DatabaseName=Meters", "sa", "123456");
        conn.setAutoCommit(false);
        System.out.println("SqlServer库数据库连接成功!");
        return conn;
    }

       2、Windows身份验证(不需要用户名和密码)

public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        Connection conn=DriverManager.getConnection("jdbc:sqlserver://192.168.10.1:1433;integratedSecurity=true;DatabaseName=Meters");
        System.out.println("SQLServer连接成功:"+conn);//这里如果能打印出来表示数据库链接成功

    }

二、连接MySQL

public static Connection getConnectionForMysql() throws ClassNotFoundException, SQLException{
        Connection conn = null;
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?useSSL=false&useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC", "root", "root");
        conn.setAutoCommit(false);
        System.out.println("MySQL数据库连接成功!");
        return conn;
    }

三、连接Oracle

 public static Connection getConnectionForOracle() throws ClassNotFoundException, SQLException {
        Connection conn = null;
        Class.forName("oracle.jdbc.driver.OracleDriver");
        conn = DriverManager.getConnection("jdbc:oracle:thin:@1127.0.0.1:1521:orcl", "test", "test");
        conn.setAutoCommit(false);
        System.out.println("Oracle库数据库连接成功!");
        return conn;
    }

四、连接Access数据库

public static Connection getConnectionForAccess() throws ClassNotFoundException, SQLException{
        Connection conn = null;
        Class.forName("com.hxtt.sql.access.AccessDriver");
        conn = DriverManager.getConnection("jdbc:Access:///E://HuaDB.mdb", username, password);
        conn.setAutoCommit(false);
        System.out.println("access库数据库连接成功!");
        return conn;
    }

这篇关于java JDBC连接sqlServer、MySQL、Oracle、Access数据库的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!