package dbu;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import jdbc.Emp;
/**
* jdbc utils
*
*/
public class DBUtils {
Connection connection;
ResultSet rSet;
Statement statement;
// 连接数据库
public Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL","scott","tiger");
System.out.println("success......");//随意去留
return connection;
}
// 查询:查询一个就是对象,查询所有就是集合。
public ResultSet query(String sql) throws ClassNotFoundException, SQLException {
statement = connection.createStatement();
rSet = statement.executeQuery(sql);
return rSet;
}
// DML操作
public int update(String sql) throws SQLException {
statement =connection.createStatement();
int i = statement.executeUpdate(sql);
return i;
}
// 释放资源
public void closed() throws SQLException {
if (rSet != null) {
rSet.close();
}if (statement != null) {
statement.close();
}if (connection != null) {
connection.close();
}
}
public static void main(String[] args) {
DBUtils dbUtils = new DBUtils();
try {
dbUtils.getConnection();
int isRight = dbUtils.update("insert into dept values(01, 'Development', 'Shanghai')");
System.out.println(isRight);
ResultSet rSet = dbUtils.query("select * from emp");
List<Emp> list = new ArrayList<>();
Iterator<Emp> it = list.iterator();
while (rSet.next()) {
Emp emp = new Emp();
emp.setEmpno(rSet.getInt("empno"));
emp.setEname(rSet.getString("ename"));
emp.setJob(rSet.getString("job"));
list.add(emp);
}
System.out.println(list.size());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Java DButil 分解
最新推荐文章于 2021-11-06 14:06:04 发布