public class JDBCTest02{
public static void main(String[] args){
Connection conn = null;
PreparedStatement ps = null;//使用PreparedStatement(预编译的数据库操作对象)
ResultSet rs = null;
try{
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","root");
//3.获取与编译的数据库操作对象
/*新增
String sql = "insert into dept(deptno,dname,loc) values(?,?,?)";
ps = conn.prepareStatement(sql);
ps.setInt(1,60);
ps.setString(2,"销售部");
ps.setString(3,"上海");
//4.执行SQL
int count = ps.executeUpdate();
System.out.println(count);
*/
/*修改
String sql = "update dept set dnmae = ? , loc = ? where deptno= ?";
ps = conn.prepareStatement(sql);
ps.setString(1,"销售一部");
ps.setString(2,"北京");
ps.setInt(1,60);
//4.执行SQL
int count = ps.executeUpdate();
System.out.println(count);
*/
/*删除
String sql = "delete from dept where deptno = ? "
ps = conn.prepareStatement(sql);
ps.setInt(1,60);
//4.执行SQL
int count = ps.executeUpdate();
System.out.println(count);
*/
/*模糊查询错误的语法
String sql = "select ename from emp where ename like '_?%'";
ps = conn.prepareStatement(sql);
ps.setString(1,"A");
*/
String sql = "select ename from emp where ename like ?";
ps = conn.prepareStatement(sql);
ps.setString(1,"_A%");
//5.处理结果集
rs = ps.executeQuery();
while(rs.next()){
System.out.println(rs.getString("ename"));
}
}catch(Exception e){
e.printStackTrace();
}finally{
//6.释放资源
if(rs!=null){
try{
rs.close();
}
catch(Exception e){
e.printStackTrace();
}
}
if(ps!=null){
try{
ps.close();
}
catch(Exception e){
e.printStackTrace();
}
}
if(conn!=null){
try{
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
}
JDBC PreparedStatement简单操作
最新推荐文章于 2023-12-09 12:04:07 发布