/**
* 通过改变配置文件来连接不同数据库
*/
package com.xykj.jdbc;
import static org.junit.Assert.*;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.util.Properties;
import org.junit.Test;
public class JDBCTest0 {
public Connection getConnection() throws Exception{
String driverclass = null;
String jdbcUrl = null;
String user = null;
String password = null;
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)Class.forName(driverclass).newInstance();
Properties info = new Properties();
info.put("user",user);
info.put("password", password);
Connection connection = driver.connect(jdbcUrl, info);
return connection;
}
@Test
public void testGetConnection() throws Exception{
System.out.println(getConnection());
}
}
/*** jdbc连接oracle数据库**/
1 package com.xykj.jdbc;
import static org.junit.Assert.*;
import java.sql.*;
import java.util.Properties;
import org.junit.Test;
public class JDBCTest {
/**
* Driver是一个接口:数据库厂商必须提供实现的接口,能从其中获取数据库连接。
* 1.加入oracle驱动
* 1>新建lib目录,复制粘贴jar包放入lib。
* 2>右键jar包,build path,add 加入到类路径下。
*/
@Test
public void testDriver() {
ResultSet res=null; //创建一个结果集对象
PreparedStatement pre = null; //创建预编译语句对象,一般都是用这个而不用Statement
Connection connection = null; //创建一个数据库连接
try
{
//1.创建一个Driver实现类的对象
Driver driver = new oracle.jdbc.driver.OracleDriver(); //加载Oracle驱动程序
//2.准备连接数据库的基本信息:url,user,password
String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
Properties info = new Properties();
info.put("user", "system");
info.put("password", "sys");
//3.调用Driver接口的connect(url,info)获取数据库连接
connection = driver.connect(url, info); //获取连接
System.out.println(connection);
System.out.println("数据库连接成功!");
//4.对数据库进行操作
String sql = "select * from Stu where Name = ?"; //预编译语句,?代表参数
pre = connection.prepareStatement(sql); //实例化预编译语句
pre.setString(1, "张三"); // 设置参数,前面的1表示参数的索引,而不是表中列名的索引
res = pre.executeQuery(); //执行查询
while(res.next())
System.out.println("姓名:"+res.getString("name")
+ "性别:"+res.getString("sex")
+ "年龄:"+res.getString("age"));
}
catch (Exception e )
{
e.printStackTrace();
}
finally
{
try
{
// 逐一将上面的几个对象关闭,因为不关闭的话会影响性能、并且占用资源
// 注意关闭的顺序,最后使用的最先关闭
if(res != null)
res.close();
if(pre != null)
pre.close();
if(connection != null)
connection.close();
System.out.println("数据库连接已关闭!");
}
catch(Exception e){
e.printStackTrace();
}
}
}
}