设为首页 加入收藏

TOP

JDBC-数据库的更新操作编程(三)
2015-11-21 01:43:54 来源: 作者: 【 】 浏览:0
Tags:JDBC- 数据库 更新 操作 编程

首先建立一个静态方法,代码如下:

public static Statement getStatement(){
        Statement st = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_dbb", "root", "");
            st = (Statement) conn.createStatement();
        } catch (Exception e) {
            // TODO: handle exception
        }
        return st;
    }

这个静态类获取Statement,通过Statement类来实现添加,更新和删除操作,分别是静态代码实现的。全部代码如下:

public static Statement getStatement(){
        Statement st = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_dbb", "root", "");
            st = (Statement) conn.createStatement();
        } catch (Exception e) {
            // TODO: handle exception
        }
        return st;
    }
    public static void insert(){
        try {
            String sql = "INSERT INTO tbl_user(name,password,email)" +
                    "VALUES('Tom','123456','tom@qq.com')";
            Statement st = getStatement();
            int count = st.executeUpdate(sql);
            System.out.println("插入了"+count+"行数据");
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    public static void update(){
        try {
            String sql = "UPDATE tbl_user SET email='tom@136.com' WHERE name='Tom'";
            Statement st = getStatement();
            int count = st.executeUpdate(sql);
            System.out.println("更新了"+count+"行数据");
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    public static void delete(){
        try {
            String sql = "DELETE FROM tbl_user WHERE name='Tom'";
            Statement st = getStatement();
            int count = st.executeUpdate(sql);
            System.out.println("删除了"+count+"行数据");
        } catch (Exception e) {
            // 
            }
        }
    public static void main(String[] args) {
                //insert();
                //update();
                delete();
    }
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇ForXMLPath 下一篇Drill中实现HTTPstorageplugin

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: