jdbc 占位符 “ ?”

 在jdbc中,当有不确定的输入时可以使用?在语句中占位,最后用set补上

 连接关闭数据

public class Demo4 {
    public static final String DBdriver = "com.mysql.cj.jdbc.Driver";
// 驱动程序管理器通过这个 URL 选择正确的驱动程序,从而建立到数据库的连接。格式 jdbc:子协议:子名称
    public static final String DBurl = "jdbc:mysql://localhost:3306/test";
    public static final String DBuser = "root";
    public static final String DBpassword = "123456";

    public static void main(String[] args) throws SQLException, ParseException {
// 开启数据库
        try {
            Class.forName(DBdriver); //加载驱动
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(DBurl,DBuser,DBpassword);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }




//最后关闭数据库
        try {
            conn.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

用 ?增加数据,整数类型,字符串类型和时间类型

// Statement:用于执行静态 SQL 语句,返回的是数字代表执行了几行。
        //Statement st = conn.createStatement();

// 使用PreparedStatement进行添加
// 在不确定的位置用"?"填充
        String sql = "insert into student (sid,sname,sage) values(?,?,?) ";
        PreparedStatement ps = conn.prepareStatement(sql);
// 根据不同的数据类型进行添加
        ps.setInt(1,1012);
        ps.setString(2,"可1");
// 对于date类型的数据,可以使用类型转换输入
        java.util.Date date1 = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss").parse("1998-03-22 22:12:22");
        java.sql.Date date2 = new Date(date1.getTime());
        ps.setDate(3, date2);
// 执行以上操作
        //ps.execute();或下面语句都可以
        int n = ps.executeUpdate();

删除数据,模糊匹配删除姓张的数据

// 删除数据
        String delete = "delete from student where sname like ?";
        PreparedStatement st = conn.prepareStatement(delete);
// 进行模糊匹配,删除所有名字以张开头的
        st.setString(1,"张%");
        st.execute();

修改数据,数据增改删都使用executeUpdate()进行操作

// 修改数据
        String update = "update student set sname = '三三' where sname = ?";
        PreparedStatement ps2 = conn.prepareStatement(update);
        ps2.setString(1, "李珊");
// 增改删都使用executeUpdate()
        ps2.executeUpdate();

对数据进行查询,使用executeQuery()

// 查找数据
        String sql1 = "SELECT * FROM student where sid=? ";
        PreparedStatement statement = conn.prepareStatement(sql1);
        statement.setInt(1,1002);
//将SQL发送给数据库服务器
        ResultSet resultSet = statement.executeQuery();
//遍历结果集
        while (resultSet.next()) {
            int id = resultSet.getInt(1);
            String name = resultSet.getString(2); // 使用getString()方法获取字符串字段
            System.out.println("id =" + id + ", name =" + name);
        }

最后关闭数据库。 

 

 

 

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值