当前位置:Gxlcms > 数据库问题 > JDBC课程1-实现Driver接口连接mysql数据库、通用的数据库连接方法(使用文件jdbc.properties)

JDBC课程1-实现Driver接口连接mysql数据库、通用的数据库连接方法(使用文件jdbc.properties)

时间:2021-07-01 10:21:17 帮助过:19人阅读

day_18; import jdk.internal.util.xml.impl.Input; import org.junit.Test; import java.io.InputStream; import java.net.URL; import java.sql.*; import java.util.Properties; import java.util.logging.Logger; /** * Driver 只是一个接口,数据库厂商必须提供的接口,能从中获取数据库连接 * 一:加载方法 * 1.加入mysql 驱动 * 2.解压 mysql-connector-java-5.1.7.zip ,复制jar文件并添加进工程中 * 3.Driver() throws Exception */ public class test1 { @Test public void testDriver() throws Exception{ ///1.创建一个Driver 实现类的对象 Driver driver = new com.mysql.jdbc.Driver(); String url="jdbc:mysql://localhost:3306/books"; //数据库所在的主机IP或者localhost //2.准备连接数据库的基本信息:url,user,password Properties info=new Properties(); info.put("user", "root"); info.put("password", "123456"); //3.调用Driver接口的 connect(url,info) 获取数据库连接 Connection connection=driver.connect(url,info); System.out.println(connection); //连接成功:输出:com.mysql.jdbc.JDBC4Connection@27ddd392 } /**二:通用的方法 * 编写一个通用的方法,在不修改源程序的情况下,可以获取任何数据库的连接 * 解决方案: * 把数据库驱动driver 实现类的全类名、url、user、password放入一个配置文件中 * 通过修改配置文件的方法 实现和具体的数据库解耦。 */ @Test //显示正常:com.mysql.jdbc.JDBC4Connection@19e1023e public void testGetConnection() throws Exception{ System.out.println(getConnection()); } public Connection getConnection() throws Exception{ String driverClass=null,jdbcUrl=null,user=null,password=null; //读取类路径下的jdbc.properties 文件 InputStream in= getClass().getClassLoader().getResourceAsStream("jdbc.properties"); Properties properties =new Properties(); properties.load(in); driverClass =properties.getProperty("driver"); jdbcUrl=properties.getProperty("jdbcUrl"); user = properties.getProperty("user"); password = properties.getProperty("password"); //运用反射新建一个通用的 driver对象 Driver driver = (Driver)Class.forName(driverClass).newInstance(); Properties info=new Properties(); info.put("user", user); info.put("password", password); //通过Driver 的connect方法获取数据库的连接 Connection connection=driver.connect(jdbcUrl, info); return connection; } }

通用的数据库连接方法需要新建:

jdbc.properties (直接建立在SRC工程下)

技术分享图片

 

JDBC课程1-实现Driver接口连接mysql数据库、通用的数据库连接方法(使用文件jdbc.properties)

标签:运用   ogg   resource   mys   c4c   jdbc   连接   取数   对象   

人气教程排行