Use dbutils additions and deletions to check the operation

Source: Internet
Author: User
Tags object object

If you are only using JDBC to develop, redundant code is too much, in order to simplify JDBC development, the Apache Commons component is a member: Dbutils.
Dbutils is the simplified Development Toolkit for JDBC. Need to use technology: Connection pool (get connection), SQL statement. 1.JavaBean Components


Code:

Package cn.itheima.domain;

public class User {
    private int uid;
    Private String uname;
    Private String Upassword;
    Public User () {

    } public
    int getuid () {return
        uid;
    }
    public void SetUid (int uid) {
        this.uid = uid;
    }
    Public String Getuname () {return
        uname;
    }
    public void Setuname (String uname) {
        this.uname = uname;
    }
    Public String Getupassword () {return
        upassword;
    }
    public void Setupassword (String upassword) {
        This.upassword = Upassword;
    }

}
2.DBUtils Overview

Dbutils is a database operation tool used in Java programming, small and simple to use.
Dbutils encapsulates JDBC operations, simplifies JDBC operations, and can write less code.
dbutils three core features:
API for SQL statement operations in Queryrunner
Resulesethandler structure that defines how a result set is encapsulated after a select operation
Dbutils class, which is a tool class that defines the methods for closing resources and practices. 3.QueryRunner Core Class

4.ResuleSetHandler result set processing class


5.DbUtils Tool Class

Closequiety (Connection conn) Closes the connection, if there is an exception try not to throw
commitandclisequietly (Connection conn) commit and close the connection
rollbackandclosequietly (Connection conn) rollback and close connection 6. Implement and modify the Operation

Package cn.itheima.jdbc.test;

Import java.sql.SQLException;
Import Org.apache.commons.dbutils.QueryRunner;

Import Org.junit.Test;
Import Cn.itheima.jdbc.utils.C3P0Utils;
    /** * Test Dbutils Tool class additions and deletions change operation * @author Administrator */public class Testdbutils {/** * Add all user methods * * @Test public void Testadduser () {//1. Create core Queryrunner queryrunner qr =new queryrunner (C3P0UTILS.GETDA
        Tasource ());
        2. Edit the SQL language sentence String sql= "insert into tbl_user values (null,?,?)";
        3. For placeholder setting value object[] params = {"Yu Huai", "Loyal"};
            4. Perform add operation try {int rows=qr.update (sql,params); if (rows>0) {System.out.println ("add success.")
            "); }else {System.out.println ("Add failed.")
            ");
        The catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace (); }/** * Modify user method based on ID * * @Test public void TestupdatEuserbyid () {//1. Create core Queryrunner queryrunner qr =new queryrunner (C3p0utils.getdatasource ()); 2. Edit SQL Syntax String sql= "Update tbl_user set upassword=?"
        where uid=? ";
        3. For placeholder settings value object[] params = {"xxx", 8};
            4. Perform add operation try {int rows=qr.update (sql,params); if (rows>0) {System.out.println ("modified successfully.")
            "); }else {System.out.println ("failed to modify.")
            ");
        The catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace (); }/** * Delete User method based on ID * * @Test public void Testdeleteuserbyid () {//1. Create core category Queryrunn
        Er queryrunner qr =new queryrunner (C3p0utils.getdatasource ());
        2. Edit the SQL language sentence String sql= "Delete from Tbl_user where uid=?";
        3. For placeholder settings value object[] params = {5};
  4. Perform add operation try {int rows=qr.update (sql,params);          if (rows>0) {System.out.println ("delete succeeded"); }else {System.out.println (delete failed.)
            ");
        The catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace ();
 }
    }

}

Run Result:




7. To perform a check operation

Package cn.itheima.jdbc.test;
Import java.sql.SQLException;
Import java.util.List;

Import Java.util.Map;
Import Org.apache.commons.dbutils.QueryRunner;
Import Org.apache.commons.dbutils.handlers.BeanHandler;
Import Org.apache.commons.dbutils.handlers.BeanListHandler;
Import Org.apache.commons.dbutils.handlers.ColumnListHandler;
Import Org.apache.commons.dbutils.handlers.MapListHandler;
Import Org.apache.commons.dbutils.handlers.ScalarHandler;

Import Org.junit.Test;
Import Cn.itheima.domain.User;
Import Cn.itheima.jdbc.utils.C3P0Utils;
    /** * Test dbutils query Operation * * @author Administrator */public class TESTDBUTILS2 {/** * query all user methods * * @Test public void Testqueryall () {try {//1. Get core class Queryrunner Queryrunner qr = new Qu
            Eryrunner (C3p0utils.getdatasource ());
            2. Write SQL statement String sql= "SELECT * from Tbl_user"; 3. Perform query operations list<user> users = qr.query (SQL, new Beanlisthandler<user> (user.class)); 4. The result set collection is traversed for (User user:users) {System.out.println (User.getuname () + ":" +user.getupas
            Sword ());
        The catch (SQLException e) {throw new RuntimeException (e); }/* * Query user method based on ID * * @Test public void Testqueryuserbyid () {try {//1. Obtained
            Take core class Queryrunner queryrunner qr = new Queryrunner (C3p0utils.getdatasource ());
            2. Write SQL statement String sql = "SELECT * from Tbl_user where uid=?";
            3. Set value for placeholder object[] params = {2};
            4. Execute query operation User user = Qr.query (sql, New beanhandler<user> (User.class), params);
        System.out.println (User.getuname () + ":" + User.getupassword ());
        catch (SQLException e) {throw new RuntimeException (e);
 * * * * Based on the total number of users * * @Test public void Testquerycount () {try {           1. Acquisition of core class Queryrunner queryrunner qr = new Queryrunner (C3p0utils.getdatasource ());
            2. Write SQL statement String sql = "SELECT COUNT (*) from Tbl_user";
            4. Execute query operation Long Count = (long) qr.query (SQL, New Scalarhandler ());
        System.out.println (count);
        catch (SQLException e) {throw new RuntimeException (e); }/* * Query all user methods */@Test public void TestQueryAll1 () {try {//1. Get Core class Que
            Ryrunner queryrunner qr = new Queryrunner (C3p0utils.getdatasource ());
            2. Write SQL statement String sql = "SELECT * from Tbl_user";
            3. Execute query operation list<map<string, object>> List = qr.query (sql, New Maplisthandler ());
            4. Iterate over the set of result sets for (map<string, object> map:list) {System.out.println (MAP); } catch (SQLException e) {throw new RuntimeException (e); }/* * Query all user methods */@Test public void TestQueryAll2 () {try {//1. Get Core class Que
            Ryrunner queryrunner qr = new Queryrunner (C3p0utils.getdatasource ());
            2. Write SQL statement String sql = "SELECT * from Tbl_user";
            3. Execute query operation list<object> List = qr.query (sql, New Columnlisthandler ("uname"));
            4. Iterate over the set of result sets for (object object:list) {System.out.println (object);
        The catch (SQLException e) {throw new RuntimeException (e);
 }
    }
}

Run Result:




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.