java实现连接mysql数据库实现增删改查功能(jdbc)

 

注意:需要手动导Driver包或maven自动导包自己选择

Statement这边就没有演示了因为存在sql注入弊端

例:SELECT * FROM users WHERE USER = '1' OR ' AND password = '=1 OR '1'= '1';

增、删、改

复制代码
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestJdbc {
    public static void main(String args[]) {
        // 1.配置信息
     String driver = "com.mysql.jdbc.Driver";
// jdbc:mysql 协议; localhost ip地址; 3306 mysql的端口号; test test数据库 String url = "jdbc:mysql://localhost:3306/test"; // mysql用户 String user = "root"; // mysql密码 String password = "abc123"; Connection conn = null; PreparedStatement ps = null; try { // 2.加载驱动 Class.forName("com.mysql.jdbc.Driver"); // 3.获取连接 conn = DriverManager.getConnection(url, user, password); // 4.预编译sql语句,返回PreparedStatement实例 // String sql = "insert into users(id,name,age,birth) value(?,?,?,?)"; ////String sql = "delete from users where id = ?"; ////String sql = "update users set age = ? where id = ?"; // 这边演示添加,使用删和改主意填充占位符也要改 ps = conn.prepareStatement(sql); // 5.填充占位符 ps.setInt(1,3); // 给第一个占位符赋值为3 ps.setString(2,"jenny"); // 给第二个占位符赋值为jenny ps.setInt(3,18); // 给第三个占位符赋值为18 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = sdf.parse("2000-01-30"); ps.setDate(4, new java.sql.Date(date.getTime())); // 6.执行操作 ps.execute(); } catch (Exception e) { e.printStackTrace(); } finally { // 7.关闭资源(先开后关) try { // 判断是否为空,防止空指针异常 if (ps != null) { ps.close(); } } catch (SQLException e) { e.printStackTrace(); } try { // 判断是否为空,防止空指针异常 if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
复制代码

复制代码
import java.sql.*;

public class TestJdbc1 {

    public static void main(String[] args) {

        String driver = "com.mysql.jdbc.Driver";// 驱动路径

        String url = "jdbc:mysql://localhost:3306/test";// 数据库地址

        String user = "root";// 访问数据库的用户名

        String password = "laixinghai";// 用户密码

        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            // 1、加载驱动
            Class.forName(driver);

            // 2、连接数据库
            con = DriverManager.getConnection(url, user, password);

            if (!con.isClosed()) {// 判断数据库是否链接成功

                System.out.println("已成功链接数据库!");

                // 3、预编译sql语句,返回PreparedStatement实例
                String sql = "select * from users";// 查询user表的所有信息
                ps = con.prepareStatement(sql);

                rs = ps.executeQuery(sql);// 查询之后返回结果集

                // 5、打印出结果
                while (rs.next()) {
                    // 1.获取当前这条数据的各个字段值
                    int id = rs.getInt("id");
                    String name = rs.getString("name");
                    int age = rs.getInt("age");
                    Date birth = rs.getDate("birth");
                    // 2.获取当前这条数据的各个字段值
//                    int id = rs.getInt(1);
//                    String name = rs.getString(2);
//                    int age = rs.getInt(3);
//                    Date birth = rs.getDate(4);
                    
                    // 方式一:
                    //System.out.println(id + "\t" + name + "\t" + age + "\t" + birth);
                    
                    // 方式二:
//                    Object[] obj = new Object[] {id,name,age,birth};
//                    for (int i = 0; i < obj.length; i++) {
//                        System.out.print(obj[i] + "\t");
//                        if (i / 3 == 1) {
//                            System.out.println();
//                        }
//                    }
                    // 方式三:将数据封装为一个对象(推荐)
                    Customer customer = new Customer(id, name, age, birth);
                    System.out.println(customer);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
class Customer {
    private int id;
    private String name;
    private int age;
    private Date birth;
    
    // 空参构造器
    public Customer() {}
    
    // 带参构造器
    public Customer(int id, String name, int age, Date birth) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.birth = birth;
    }
    // 提供get、set方法
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    public Date getBirth() {
        return birth;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    
    // 重写toString
    @Override
    public String toString() {
        return "Customer [id=" + id + "\tname=" + name + "\tage=" + age + "\tbirth=" + birth +"]";
    }
}
复制代码

 

posted @   lai_xinghai  阅读(927)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示