Java_jdbc 基础笔记之二 数据库连接
2015-09-04 18:28
591 查看
/** * DriverManager 类是驱动程序管理器类 * 1)可以通过重载的getConnection()方法获取数据库的连接,较为方便 * 2)可以同时管理多个驱动程序:若注册了多个数据库连接, 则调用getConnection()方法时传入的参数不同, 则返回不同的数据库的连接; * * @throws Exception * * @throws Exception * /
@Test public void testDriverManager() throws Exception { // 1 准备连接数据库的4个字符串。 // 驱动的全类名 String driverClass = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "admin"; String driverClass1 = "oracle.jdbc.driver.OracleDriver"; String url1 = "jdbc:oracle:thin:@localhost:1521:orcl"; String user1 = "scott"; String password1 = "tiger"; // 2 加载数据库的驱动程序(对应的Driver 实现类中有注册驱动的静态代码块) Class.forName(driverClass1); // 3 通过DriverManager的getConnection()方法获取数据库的连接。 Connection connection = DriverManager.getConnection(url1, user1, password1); System.out.println(connection); } // 将其封装为方法 public Connection getConnection1() throws Exception { // 1、首先 准备连接数据库的4个字符串 String driverClass = null; String urljdbc = null; String user = null; String password = null; // 2、读取配置文件 InputStream is = getClass().getClassLoader().getResourceAsStream( "jdbc.properties"); Properties properties = new Properties(); // 加载 properties.load(is); driverClass=properties.getProperty("driver"); urljdbc=properties.getProperty("urljdbc"); user=properties.getProperty("user"); password=properties.getProperty("password"); //3、加载数据库的驱动程序(对应的Driver 实现类中有注册驱动的静态代码块) Class.forName(driverClass).newInstance(); // 4 通过DriverManager的getConnection()方法获取数据库的连接。 Connection conn=DriverManager.getConnection(urljdbc, user, password); return conn; } @Test public void testConnection1() throws Exception{ System.out.println(getConnection1()); } }
相关文章推荐
- jdbc中的Statement和PreparedStatement接口对象
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android之获取手机上的图片和视频缩略图thumbnails
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- 插入排序
- 冒泡排序
- 堆排序