JDBC学习笔记

jdbc需要加载的:
Driver:驱动
DriverManager:驱动管理器
Connection:连接
Statement: 清单对象/执行器
PreparedStatement: 预处理
——Query (DQL)
——Update (DML)
ResultSet:结果集
ResultSetMetadata:本次查询的列的结构

*基本操作步骤:
1.导入数据库jar包
2.加载驱动
3.建立连接(Connection)
4.向数据库发送sql请求(String类型sql语句,Statement)
5.返回结果集(ResultSet),并对结果进行相应操作。
6.关闭连接*

注:程序员可以手动的去操控事务(true默认提交–连接正常关闭当做commit去处理,false事务不会自动提交)
在建立连接后输入
connection.setAutoCommit(false);
(若参数为true代表自动提交,false代表手动提交)
之后可调用connection.commit();或connection.rollback();进行提交或回滚

一、连接Oracle数据库,进行查询:
//数据库参数
String driverName = “oracle.jdbc.driver.OracleDriver”;
String url = “jdbc:oracle:thin:@127.0.0.1:1521:orcl”;
String user = “scott”;
String password = “tiger”;
/**
* 尝试连接数据库
* @throws ClassNotFoundException
* @throws SQLException
*/
private static void testOracleDql(String driverName, String url, String user, String password) throws ClassNotFoundException, SQLException {
//加载驱动
Class.forName(driverName);
//获取连接
Connection connection = DriverManager.getConnection(url, user, password);
//向数据发送sql请求(切记:不要加分号)
String sql = “SELECT * FROM EMP”;
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
//遍历并查看结果集的内容
while (resultSet.next()) {
System.out.print(resultSet.getInt(“empno”) + “\t” + resultSet.getString(“ename”));
System.out.println();
}
//关闭连接
resultSet.close();
statement.close();
connection.close();
}

二、修改数据库
private static void testOracleDml(String driverName, String url, String user, String password) throws ClassNotFoundException, SQLException {
//加载驱动
Class.forName(driverName);
//获取连接
Connection connection = DriverManager.getConnection(url, user, password);
//获取执行对象
Statement statement = connection.createStatement();
//发送请求
// String sql = “DELETE FROM EMP WHERE EMPNO = 7788”;
// String sql = “UPDATE EMP SET ENAME = ‘BJSXT’ WHERE EMPNO = 7900”;
// String sql = “INSERT INTO EMP VALUES(9999,’ZHANGSAN’,’STUDENT’,7900,SYSDATE,4000,NULL,10)”;
String sql = “INSERT INTO EMP VALUES(8888,’ZHANGSAN’,’STUDENT’,7900,TO_DATE(‘2015-04-14’,’YYYY-MM-DD’),4000,NULL,10)”;
int count = statement.executeUpdate(sql);
System.out.println(“受影响的行数为:” + count);
//释放资源,关闭连接
statement.close();
connection.close();
}

你可能感兴趣的:(个人学习,jdbc)