Spring JdbcTemplate: Three Ways to query (single value, single object, object collection)

Source: Internet
Author: User

Jdbctemplatedemo2.java

Package Helloworld.jdbctemplate;import Org.springframework.jdbc.core.jdbctemplate;import Java.sql.*;import java.util.list;/** * Function: query operation via JdbcTemplate * Query results need to be encapsulated (implement RowMapper interface) */public class JdbcTemplateDemo2 {//        JdbcTemplate Use steps://1, Import jar package, 2, set the database information, 3, set the data source, 4, call the method in the JdbcTemplate object to implement the operation public static void main (string[] args) {        Set database information and data source jdbctemplateobject Jdbctemplateobject = new Jdbctemplateobject (); JdbcTemplate JdbcTemplate = Jdbctemplateobject.getjdbctemplate ();//Insert Data//InsertData ();//query returns a value: Check        The total number of data in the table Queryforone (jdbctemplate);//Query returns Object queryForObject (JdbcTemplate);//query returns list collection    queryForList (JdbcTemplate);//use JDBC to implement query Querywithjdbc (); }//Insert data public static void InsertData () {Jdbctemplateobject jdbctemplateobject = new Jdbctemplateobject ()        ; JdbcTemplate JdbcTemplate = Jdbctemplateobject.getjdbctemplate ();//Call the method in the JdbcTemplate object to implement the Operation StrinG sql = "INSERT into user value (?,?,?)";        Table structure: ID (int, self-increment), name (varchar), age (int) int rows = jdbctemplate.update (sql, NULL, "Tom", 35);    System.out.println ("Number of inserted rows:" + rows);  /** * Query returns a value: Total number of data in query table */public static void Queryforone (JdbcTemplate jdbctemplate) {String sql =        "SELECT COUNT (*) from user";//Call method to get the number of records int count = Jdbctemplate.queryforobject (sql, Integer.class);    SYSTEM.OUT.PRINTLN ("Total data:" + count); }/** * Function: Query returns single Object * Step: New Myrowmapper class implement RowMapper interface, override Maprow method, specify return User Object */public static void Queryfo Robject (JdbcTemplate jdbctemplate) {String sql = "SELECT * from user where name =?"; /New Myrowmapper class implements the RowMapper interface, overriding the Maprow method, specifying the return user Object User user = Jdbctemplate.queryforobject (sql, new myrowma        Pper (), "Tom");    SYSTEM.OUT.PRINTLN (user); }/** * Function: Query return object collection * Step: New Myrowmapper class implement RowMapper interface, override Maprow method, specify return User Object */public static void QueryfoRList (JdbcTemplate jdbctemplate) {String sql = "SELECT * from user";//The third argument can be omitted list<user> us        ers = jdbctemplate.query (sql, New Myrowmapper ());    System.out.println (users);        }/** * uses the JDBC underlying implementation query */public static void Querywithjdbc () {Connection conn = null;        PreparedStatement psmt = null;        ResultSet rs = null;        String Jdbcurl = "Jdbc:mysql://192.168.184.130:3306/gxrdb"; try {//Load driver Class.forName ("Com.mysql.jdbc.Driver");//CREATE Connection conn = Drivermanag            Er.getconnection (Jdbcurl, "root", "root"); String sql = "SELECT * from user where name =?"; /precompiled SQL PSMT = conn.preparestatement (sql);//starting from 1, there is no need to psmt.setstring (1, "T Om ");//Execute SQL RS = Psmt.executequery ();//int num = Psmt.executeupdate (); Delete and change, return the operation record number//traverse result set while (Rs.next ()) {/////query the corresponding column nameValue, or it can be the position ordinal String name = rs.getstring ("name");                String age = rs.getstring ("Age");                SYSTEM.OUT.PRINTLN (name);            System.out.println (age);        }} catch (Exception e) {e.printstacktrace ();                } finally {try {rs.close ();                Psmt.close ();            Conn.close ();            } catch (SQLException e) {e.printstacktrace (); }        }    }}

Myrowmapper.java

Package Helloworld.jdbctemplate;import Org.springframework.jdbc.core.rowmapper;import Java.sql.ResultSet;import java.sql.sqlexception;/** * Implement RowMapper interface, return User Object * */public class Myrowmapper implements rowmapper<user>{    @Override public    User maprow (ResultSet ResultSet, int i) throws SQLException {//        get data in result set        String name = ResU Ltset.getstring ("name");        String age = resultset.getstring ("Age");//        encapsulates the data into a user object        user user = new user ();        User.setname (name);        User.setage (age);        return user;    }}

Jdbctemplateobject.java

 Packagehelloworld.jdbctemplate;Importorg.springframework.jdbc.core.JdbcTemplate;ImportOrg.springframework.jdbc.datasource.DriverManagerDataSource;/*** Function: Set the database information and data source * * Jdbctemplat use * 1, import jar package, 2, set database information, 3, set data source, 4, call method in JdbcTemplate object to implement Operation*/ Public classJdbctemplateobject {Drivermanagerdatasource dataSource;    JdbcTemplate JdbcTemplate;  PublicJdbctemplateobject () {//Setting Up Database information         This. DataSource =NewDrivermanagerdatasource ();  This. Datasource.setdriverclassname ("Com.mysql.jdbc.Driver");  This. Datasource.seturl ("Jdbc:mysql://192.168.184.130:3306/gxrdb");  This. datasource.setusername ("root");  This. Datasource.setpassword ("root");//set up a data source         This. JdbcTemplate =NewJdbcTemplate (DataSource); }     PublicDrivermanagerdatasource Getdatasource () {returnDataSource; }     Public voidSetdatasource (Drivermanagerdatasource dataSource) { This. DataSource =DataSource; }     PublicJdbcTemplate getjdbctemplate () {returnJdbcTemplate; }     Public voidsetjdbctemplate (JdbcTemplate jdbctemplate) { This. JdbcTemplate =JdbcTemplate; }}

User.java

 Packagehelloworld.jdbctemplate;/*** Data Encapsulation class **/ Public classUser {PrivateString name; PrivateString age;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString getage () {returnAge ; }     Public voidsetage (String age) { This. Age =Age ; } @Override PublicString toString () {return"user{Name:" + name + "; Age: "+ Ages +"} "; }}

Spring JdbcTemplate: Three Ways to query (single value, single object, object collection)

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.