JDBC学习(一)
一、Connection连接数据池
/**
*Connection代表应用程序和数据库的一个连接
**/
通过properties类加载jdbc.properties配置文件
@Test
public void testGetConnection() throws Exception{
//0.读取jdbc.properties
/**
* 1).属性文件对应Java中的Properties类
* 2).使用类加载器加载bin目录(类路径下)的文件
*/
Properties properties = new Properties();
InputStream in = ReviewTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
properties.load(in);
//1.准备获取连接的4个字符串
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String jdbcUrl = properties.getProperty("jdbcUrl");
String driverClass = properties.getProperty("driverClass");
//2.加载驱动:Class.forName(driverClass);
Class.forName(driverClass);
//3.调用
//DriverManager.getConnection(jdbcUrl,user,password)
//获取数据库连接
Connection conn = DriverManager.getConnection(jdbcUrl, user, password);
}
二、 statement操作
通过statement对数据库进行操作
public void teststatement() {
Connection connection = null;
Statement statement = null;
try {
//1.获取数据库连接
connection = getConnection();
//2.调用connection对象的createStatement对象
statement =connection.createStatement();
//3.准备SQL语句
String sql = "UPDATA ";
//4.发送SQL语句:调用Statement对象的executeUpdate(sql)方法
statement.executeQuery(sql);
//5.关闭数据库资源:由里向外关闭
statement.close();
connection.close();
} catch (Exception e) {
// TODO: handle exception
}finally {
releaseDB(null, statement, connection);
}
}
编写异常方法
public void releaseDB(ResultSet re,Statement statement,Connection connection) {
if(re != null) {
try {
re.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
if(statement != null) {
try {
statement.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
查询操作
//查询操作
public void testResultSet() {
Connection connection = null;
Statement statement = null;
ResultSet re =null;
//1.获取数据库连接
connection = getConnection();
//2.调用connection对象的createStatement对象
statement =connection.createStatement();
//3.准备SQL语句
String sql = "SELECT ";
//4.发送SQL语句:调用Statement对象的executeUpdate(sql)方法
//得到结果集对象ResultSet
re = statement.executeQuery(sql);
//5.处理结果集:
//5.1调用ResultSet的next()方法:查看结果集的下一条记录是否有效
//若有效则下移指针
while(re.next()) {
//5.2getXxx()方法获取具体的列的值
int id = re.getInt(1);
}
}