龙空技术网

如何更简洁地对数据库进行增删改

CameSawConquer 148

前言:

此时我们对“数据库中的修改语句”大致比较讲究,大家都想要知道一些“数据库中的修改语句”的相关知识。那么小编同时在网摘上汇集了一些有关“数据库中的修改语句””的相关内容,希望同学们能喜欢,你们快快来了解一下吧!

#头条创作挑战赛#

使用Spring Template

导入下面的包和log4j.properties文件

创建一个实体类User

package com.gec.bean;public class User {    private int id;    private String username;    private String password;    public User() {    }    @Override    public String toString() {        return "User{" +                "id=" + id +                ", username='" + username + '\'' +                ", password='" + password + '\'' +                '}';    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }}

写一个测试类看看能不能获取连接对象

 @Test    public void fun1() throws PropertyVetoException, SQLException {        //数据源        ComboPooledDataSource dataSource=new ComboPooledDataSource();         dataSource.setDriverClass("com.mysql.jdbc.Driver");         dataSource.setJdbcUrl("jdbc:mysql:///hrm");         dataSource.setUser("root");         dataSource.setPassword("root");        System.out.println("dataSource: "+dataSource);        //jdbcTemplate        JdbcTemplate template=new JdbcTemplate();        template.setDataSource(dataSource);        //获取连接对象        Connection connection = dataSource.getConnection();        System.out.println("connection: "+connection);    }

如果获取连接成功,则使用JdbcTemplate封装类对数据库进行增删改。

 JdbcTemplate template; ComboPooledDataSource dataSource;    @Before    public void before() throws PropertyVetoException {        //数据源        dataSource=new ComboPooledDataSource();        dataSource.setDriverClass("com.mysql.jdbc.Driver");        dataSource.setJdbcUrl("jdbc:mysql:///hrm");        dataSource.setUser("root");        dataSource.setPassword("root");        System.out.println("dataSource: "+dataSource);        //jdbcTemplate        template=new JdbcTemplate();        template.setDataSource(dataSource);    } @Test    public void fun2(){       //插入一个用户数据        int add=template.update("INSERT INTO t_user (username,PASSWORD)VALUES('张三','123')");        System.out.println("添加成功: "+add);    }    @Test    public void fun3(){        //修改一个用户数据        int update=template.update("UPDATE t_user SET username=? WHERE id=? ","苏九歌",18);        System.out.println("修改成功: "+update);    }    @Test    public void fun4(){        //删除一个用户数据        int delete=template.update("DELETE FROM t_user WHERE id=? ",20);        System.out.println("删除成功: "+delete);    }

没有修改前的数据

增加后的数据

修改后的数据

删除后的数据

标签: #数据库中的修改语句