JAVA-JDBC Tool Class Dbutils

Source: Internet
Author: User

Tag: Time object main HTTP man test close source puts

To create a project:

Import the appropriate jar package:

See.

Jdbcutil.java get the database connection file:

Package Com.gordon.jdbcutil;import Java.io.inputstream;import Java.sql.connection;import Java.sql.DriverManager; Import Java.sql.preparedstatement;import Java.sql.resultset;import Java.sql.sqlexception;import Java.util.properties;public class Jdbcutil {public static string drivername = Null;public static string URL = Null;public static string USER = Null;public static string PASSWORD = Null;public static Connection conn = null;static {try {Propertie s props = new Properties (),//reader in = new FileReader ("Db.properties"), InputStream in = JDBCUtil.class.getClassLoader () . getResourceAsStream ("Db.properties");p rops.load (in);D rivername = Props.getproperty ("drivername"); url = props.getproperty ("url"); user = Props.getproperty ("user"); PASSWORD = Props.getproperty ("PASSWORD");} catch (Exception e) {throw new RuntimeException (e);}} public static Connection getconnection () throws Exception {if (conn! = null) {return conn;} Class.forName (drivername); conn = Drivermanager.getconnection (URL, USER, PasswoRD); return conn;} public static void Closeresource (Connection conn, PreparedStatement St) throws SQLException {st.close (); Conn.close ();} public static void Closeresource (Connection conn, ResultSet RS, PreparedStatement St) throws SQLException {St.close (), Rs. Close (); Conn.close ();}}

  

JavaBean class Authoring (User.java):

Package Com.gordon.bean;public class User {private int id;private String name;public User () {}public int getId () {return I D;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;}}

  

Jdbcutils.java Database Tools Class:

Package Com.gordon.jdbcutils;import Java.sql.connection;import Java.util.list;import Org.apache.commons.dbutils.queryrunner;import Org.apache.commons.dbutils.handlers.arrayhandler;import Org.apache.commons.dbutils.handlers.arraylisthandler;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.ScalarHandler; Import Com.gordon.bean.user;import Com.gordon.jdbcutil.jdbcutil;public class Jdbcutils {public static void main (String [] args) {try {//InsertFunction ();//UpdateFunction ();//DeleteFunction (); Selectfunction ();} catch (Exception e) { System.out.println (E.getmessage ());}} public static void Selectfunction () throws Exception {/*arrayhandler encapsulates the first record in the result set into a object[] array, Each element in the array is the value of each field in the record Arraylisthandler encapsulates each record in the result set into a object[] array, encapsulating the arrays in the list collection. Beanhandler encapsulates the first record in the result set into a specified javabean. Beanlisthandler encapsulates each record in the result set to the specified JavabeAn, encapsulating these javabean in the list collection Columnlisthandler the field values of the columns specified in the result set into a list collection Scalarhandler it is used for single data. For example, select COUNT (*) from table operation. */queryrunner qr = new Queryrunner (); Connection conn = jdbcutil.getconnection ()/** arrayhandler *///1String sql = "SELECT * from user LIMIT?"; O Bject[] params = {1};object[] Objarrayhandler = qr.query (conn, SQL, New Arrayhandler (), params); System.out.println (Objarrayhandler[0] + ":" + objarrayhandler[1]);//2String sql = "SELECT * from user"; object[] params = {}; list<object[]> Listobjarrayhandler = qr.query (conn, SQL, New Arraylisthandler (), params); for (object[] Obj:listob Jarrayhandler) {System.out.println (obj[0] + ":" + obj[1]);} /** beanhandler *///1String sql = "SELECT * from user LIMIT 1"; object[] params = {}; User user = Qr.query (conn, SQL, new Beanhandler<user> (User.class), params); System.out.println (User.getid () + ":" + user.getname ());//2String sql = "SELECT * from user"; object[] params = {}; List<user> userlist = qr.query (conn, SQL, newBeanlisthandler<user> (User.class), params); for (User user:userlist) {System.out.println (User.getid () + ":" + User.getname ());} /** columnlisthandler *///1String sql = "SELECT Max (ID) from user"; object[] params = {};int Maxid = qr.query (conn, SQL, n EW scalarhandler<integer> (), params); System.out.println (MAXID);//2String sql = "SELECT name from user"; object[] params = {}; list<string> usernamelist = qr.query (conn, SQL, New columnlisthandler<string> (), params); for (String Username:usernamelist) {System.out.println (userName);}} public static void DeleteFunction () throws Exception {queryrunner qr = new Queryrunner (); String sql = "DELETE from user WHERE ID =?"; O bject[] param = {5}; Connection conn = jdbcutil.getconnection (), int res = QR.UPDATE (conn, SQL, param), if (res > 0) {System.out.println ("dele Te success. "); else if (res = = 0) {System.out.println ("deleted.");} else {System.out.println ("delete faild.");}} public static void UpdateFunction () throws Exception {queryrunner qr = new Queryrunner (); String sql = "UPDATE user SET name =?" WHERE ID =? "; O bject[] param = {"NewName", 5}; Connection conn = jdbcutil.getconnection (), int res = QR.UPDATE (conn, SQL, param), if (res > 0) {System.out.println ("Upda Te success. "); else {System.out.println ("update faild.");}}  public static void InsertFunction () throws Exception {/** Gets the execution object */queryrunner qr = new Queryrunner ();/** SQL */string sql = "INSERT into user (name) VALUES (?)"; * * parameter */object[] param = {"testname"};/** Get database connection */connection conn = Jdbcutil.getconnection ();/** Execute SQL */int res = qr. UPDATE (conn, SQL, param),/** processing result */if (Res > 0) {System.out.println ("insert success.");} else {System.out.println ("in SERT faild. ");}}

  

JAVA-JDBC Tool Class Dbutils

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.