JavaJDBC-创建Connection对象

JDBC-创建Connection对象

 

一、通过代码设置(项目更改时需要重新编译)

 

(1)、提供三个基本信息(url、user、password)

String url="jdbc:mysql://localhost:3306/test";

String user="root";

String password="2017071028";

(2)、加载驱动,不需要显示注册驱动

//mysql
Class.forName("com.mysql.cj.jdbc.Driver");

(3)、获取连接

Connection conn=DriverManager.getConnection(url,user,password);

 

二、通过配置文件设置(推荐使用)

 

将数据库连接需要的基本信息声明在配置文件当中,通过配置文件的方式,获取连接

好处:1.实现数据和代码分离,实现了解耦

           2.如果需要修该配置信息,可以避免程序重新打包

 

(1)、创建 .properties文件,保存在当前项目src下

(2)、编辑配置文件内容(四个基本信息)

user=UserName
password=PassWors

url=jdbc:mysql://localhost:3306/test
driverClass=com.mysql.cj.jdbc.Driver

(3)、调用配置文件创建Connection对象

①读取配置文件中四个基本信息

InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");



Properties pros=new Properties();

pros.load(is);

String user=pros.getProperty("user");

String password=pros.getProperty("password");

String url=pros.getProperty("url");

String driverClass=pros.getProperty("driverClass");

②加载驱动

Class.forName(driverClass);

③获取连接

Connection conn= DriverManager.getConnection(url,user,password);

 

实例一、通过配置文件设置

public static Connection getConnection()throws Exception

{

    //1.读取配置文件中四个基本信息



    InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");



    Properties pros=new Properties();

    pros.load(is);

    String user=pros.getProperty("user");

    String password=pros.getProperty("password");

    String url=pros.getProperty("url");

    String driverClass=pros.getProperty("driverClass");



    //2.加载驱动

    Class.forName(driverClass);



    //3.获取连接

    Connection conn= DriverManager.getConnection(url,user,password);

   // System.out.println(conn);

    return conn;

}
 

 

实例二、代码实现

public void test4()throws Exception

    {

        //1.提供三个连接的基本信息

        String url="jdbc:mysql://localhost:3306/test";

        String user="root";

        String password="2017071028";

        //2.加载驱动,不用显式注册驱动

        Class.forName("com.mysql.cj.jdbc.Driver");



        //3.获取连接

        Connection conn=DriverManager.getConnection(url,user,password);

        System.out.println(conn);

    }

 

posted @ 2020-08-04 22:41  orz江小鱼  阅读(1363)  评论(0编辑  收藏  举报