public static void main(String[] args) {
Connection conn = null;// 特定的数据库链接对象
try {
// 通过DriverManager与Connection的连接
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:orcl", "dhee", "dhee");
String sql = "select first_name ,last_name from employees where employee_id = ?and last_name=?";
// Statement可以用来执行SQL语句
// 多次执行SQL语句使用PreparedStatement进行预编译,效率高
PreparedStatement pt = conn.prepareStatement(sql);
pt.setString(1, "100");// 使用set方法赋值
pt.setString(2, "abc");
// ResultSet用来封装查询得到的结果
// executeQuery执行查询语句,返回结果集
ResultSet rs = pt.executeQuery();
// 必须用next()方法才能处理结果集
if (rs.next()) {
System.out.println(rs.getString(1) + "****" + rs.getString(2));
} else {
System.out.println("查无此人");
}
int i = 0;
sql = "insert into departments values(?,?,?,?)";
pt = conn.prepareStatement(sql);
pt.setString(1, "30");
pt.setString(2, "dhc");
pt.setString(3, "200");
pt.setString(4, "1700");
// executeUpdate执行增删改,返回操作的行数
i = pt.executeUpdate();
if (i > 0) {
System.out.println("插入数据成功");
}
sql = "update departments set department_name = ? where department_id =?";
pt = conn.prepareStatement(sql);
pt.setString(1, "su");
pt.setString(2, "110");
i = pt.executeUpdate();// 执行增删改
if (i > 0) {
System.out.println("更改数据成功");
}
sql = "delete from departments where department_id=?";
pt = conn.prepareStatement(sql);
pt.setString(1, "30");
i = pt.executeUpdate();
if (i > 0) {
System.out.println("删除数据成功");
}
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
数据库文章链接
JDBC