JDBC

来源:互联网 发布:美国经济数据发布时间 编辑:程序博客网 时间:2024/06/17 17:10
public void queryAll() {        Connection connection = null;        PreparedStatement ps = null;        ResultSet rs = null;        try {            Class.forName("com.mysql.jdbc.Driver");            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bz?characterEncoding=utf-8&useUnicode=true",                    "root", "123321");            String sql = "select * from cart";            ps = connection.prepareStatement(sql);            rs = ps.executeQuery();            while (rs.next()) {                System.out.printf("商品名:%s\t商品价格:%f\t购买数量: %d\n", rs.getString("name"), rs.getFloat(3), rs.getInt(4));            }        } catch (Exception e) {            e.printStackTrace();        }    }    public void insert(Goods goods) {        Connection connection = null;        PreparedStatement ps = null;        ResultSet rs = null;        try {            Class.forName("com.mysql.jdbc.Driver");//加载驱动            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bz?characterEncoding=utf-8&useEncode=true",                    "root", "123321");            String sql = "insert into cart(name,price,number) values(?,?,?)";            ps = connection.prepareStatement(sql);            ps.setString(1, goods.getName());            ps.setFloat(2, goods.getPrice());            ps.setInt(3, goods.getNumber());            System.out.println(ps.executeUpdate() > 0 ? "yes" : "no");        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                if (connection != null) {                    connection.close();                }                if (ps != null) {                    ps.close();                }            } catch (SQLException e) {                e.printStackTrace();            }        }    }    public void delete(Goods goods) {        Connection conn = null;        PreparedStatement ps = null;        try {            Class.forName("com.mysql.jdbc.Driver");            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bz?characterEncoding&useUnicode=true",                    "root", "123321");            String sql = "delete from cart where name=? and price=? and number=?";            ps = conn.prepareStatement(sql);            ps.setString(1, goods.getName());            ps.setFloat(2, goods.getPrice());            ps.setInt(3, goods.getNumber());            System.out.println(ps.executeUpdate() > 0 ? "yes" : "no");        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                if (conn != null) {                    conn.close();                }                if (ps != null) {                    ps.close();                }            } catch (SQLException e) {                e.printStackTrace();            }        }    }
原创粉丝点击