0
点赞
收藏
分享

微信扫一扫

四步手把手教你使用java程序来创建mysql的jdbc连接对象-方式二


四步手把手教你使用java程序来创建mysql的jdbc连接对象-方式二

首先展示一下之前方式一获取连接对象的方式:

Class clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver= (Driver) clazz.newInstance();
String url= "jdbc:mysql://localhost:3306/myemployees";
Properties properties=new Properties();
properties.setProperty("user","root");
properties.setProperty("password","****");
Connection connect = driver.connect(url, properties);
System.out.println(connect);

我们其实会发现,这个代码的可移植性太差,也就是,当我们换了数据库的时候,代码也需要进行修改,为了动态实现,我们想到使用反射来获取Driver类,而不想在程序里面体现第三方。
之前加载mysql驱动时采用多态去new Driver子类实现类。
Driver driver=new com.mysql.jdbc.Driver();
现在通过反射动态去获取驱动
先通过Class。for Name()方法去获取它的Class对象
Class clazz=Class.forName(“com.mysql.jdbc.Driver”);
再通过class对象的newInstance()方法获取Class类的具体类实例
Driver driver=(Driver)clazz.newInstance();
其他的都一样

上代码:

Class clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver= (Driver) clazz.newInstance();
String url= "jdbc:mysql://localhost:3306/myemployees";
Properties properties=new Properties();
properties.setProperty("user","root");
properties.setProperty("password","****");
Connection connect = driver.connect(url, properties);
System.out.println(connect);

``
![在这里插入图片描述](https://img-blog.csdnimg.cn/20201204143012446.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxNzA5NTc3,size_16,color_FFFFFF,t_70)

同样执行代码后,打印获取的连接对象的地址。


举报

相关推荐

0 条评论