MySQL jdbc增删改查

来源:互联网 发布:明道办公软件登陆 编辑:程序博客网 时间:2024/06/06 20:13

步骤

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();        }    }}
0 0
原创粉丝点击