import com.sun.tools.javac.Main;
import java.sql.*;
/**
* @author zzw
* @create 2020/11/16-10:55
*/
public class jdbcTest09 {
public static void main(String[] args) {
//jdbc6步走
Connection conn = null;
PreparedStatement ps = null;
int count ;
try {
//1、注册驱动
Driver driver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);
//2、获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "a");
/*
给数据库增加一个数据
//3、获取数据库操作对象
String sql = "insert into jdbc01(语文,数学,英语) values (?,?,?)";
ps = conn.prepareStatement(sql);
//编译之后给占位符赋值
ps.setInt(1,60);
ps.setInt(2,60);
ps.setInt(3,60);
//4、执行sql,根据数据库的操作不同,使用不同的PreparedStatement方法,这里我们使用executeUpdate()
count = ps.executeUpdate();
System.out.println(count);
*/
/*
数据更新,修改
//3、获取数据库操作对象
//String sql = "update jdbc01 set 语文=?,数学=?,英语=?";这个就全部改了
String sql = "update jdbc01 set 语文=?,数学=? where 英语=?";
ps = conn.prepareStatement(sql);
//编译之后给占位符赋值
ps.setInt(1,70);
ps.setInt(2,70);
ps.setInt(3,80);
//4、执行sql,根据数据库的操作不同,使用不同的PreparedStatement方法,这里我们使用executeUpdate()
count = ps.executeUpdate();
System.out.println(count);
*/
//3、获取数据库操作对象
String sql="delete from jdbc01 where 语文=?";
ps = conn.prepareStatement(sql);
//编译之后给占位符赋值
ps.setInt(1,70);
//4、执行sql,根据数据库的操作不同,使用不同的PreparedStatement方法,这里我们使用executeUpdate()
count = ps.executeUpdate();
System.out.println(count);
//5、处理查询结果集
} catch (SQLException e) {
e.printStackTrace();
} finally {
//6、释放资源
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
JDBC学习----09--PreparedStatement完成增删改
最新推荐文章于 2024-07-12 22:52:40 发布