四步手把手教你使用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);
``

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