MySQL jdbc增删改查

步骤

public class MySql {

    public static void main(String[] args) {
        //连接数据库的驱动
        String driver = "com.mysql.jdbc.Driver";
        //URL指向要访问的数据库名
        String url = "jdbc:mysql://localhost:3306/calzz";
        //MYSQL的用户名
        String user = "root";
        //MySQL的密码
        String password = "123456";

        try {
            Class.forName(driver);//加载驱动
            Connection connection = DriverManager.getConnection(url,user,password);//连接数据库
            if(!connection.isClosed()){
                //数据库操作类
                Statement statement = connection.createStatement();
                String sql;
                //执行语句
                //增
//              sql = "insert into student (name,age,sex) values('李四',23,1)";
//              statement.execute(sql);
//              //删
//              sql = "delete from student where name = '张三'";
//              statement.execute(sql);
                //改
//              sql = "update student set age = 23,sex = 0 where name ='李四'";
//              statement.execute(sql);
                //查     使用其他方法
                sql = "select name,age,sex from student where age>10";
//              statement.execute(sql);
                ResultSet resultSet = statement.executeQuery(sql);
                resultSet.first();//先把游标移到第一位
                while(!resultSet.isAfterLast()){//判断是否移到最后
                    String name = resultSet.getString("age");
                    System.out.println(name);
                    resultSet.next();
                }
                statement.close();
                connection.close();
            }else{
                System.out.println("请打开数据库连接");
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值