JDBC Tool class

Source: Internet
Author: User

1. Connect to the database

Package Com.society.demo;import java.sql.*;import java.util.properties;/** * Connection Database * * @author Liyulin [email prote    CTED] * @version 1.0 2015-01-14 */public class DBConnection {private Connection con = null;    Private String user = "root";    Private String Password = "lyl123";    Private String ServerIP = "localhost";    Private String Database = "xheditor_db";        Public DBConnection () {} public DBConnection (String database, String serverip) {this.database = database;    This.serverip = ServerIP; /** * Load Driver Establish database connection * * @throws classnotfoundexception * @throws instantiationexception * @throws Illegalaccessexception * @throws SQLException */public void Connect () throws ClassNotFoundException, Instantia        Tionexception, Illegalaccessexception, SQLException {Properties PR = new Properties ();        Pr.put ("characterencoding", "UTF-8");        Pr.put ("Useunicode", "TRUE");        Pr.put ("User", This.user); pr.Put ("password", This.password);        Class.forName ("Com.mysql.jdbc.Driver"). newinstance (); con = drivermanager.getconnection ("jdbc:mysql://" + This.serverip + "/" + This.database + "? Characterencoding=utf-8", PR)    ; }/** * Close connection */public void disconnect () {try {if (con! = null) {Con.clo            SE ();        }} catch (SQLException ex) {ex.printstacktrace ();    }}/** * Get Connection Object */Public Connection Getcon () {return con; }}

2. Operation Database

Package Com.society.demo;import Java.sql.connection;import Java.sql.preparedstatement;import java.sql.ResultSet; Import Java.sql.sqlexception;import java.sql.statement;import Java.util.arraylist;import Java.util.List;import Java.util.logging.level;import java.util.logging.logger;/** * JDBC Tool class * * @author Liyulin [email protected] * @vers    Ion 1.0 2015-01-14 */public class JDBC {private DBConnection db = null;    PRIVATE Connection conn = null;    Private PreparedStatement PS = null;    Private ResultSet rs = null;        /** * Establish database connection */public Connection Connectdb () {db = new DBConnection ();            try {db.connect ();        conn = Db.getcon ();        } catch (Exception ex) {Logger.getlogger (JDBC.class.getName ()). log (Level.severe, NULL, ex);    } return conn; /** * Close Database */public void Closedb () {try {if (rs! = null) {Rs.close ()            ; } if (PS! = null) {               Ps.close ();            } if (conn! = null) {conn.close ();        }} catch (SQLException ex) {Logger.getlogger (JDBC.class.getName ()). log (Level.severe, NULL, ex); }}/** * executes an SQL statement (add, delete, change) * * @param SQL INSERT SQL statement * @param the params SQL statement? The corresponding value * @return whether to insert into        function */public boolean executesql (String sql, object[] params) {connectdb ();            try {PS = conn.preparestatement (SQL);                    if (null! = params) {for (int i = 0, paramssize = params.length; i < paramssize; i++) {                Ps.setobject (i + 1, params[i]); }} return (Ps.executeupdate () > 0)?        True:false;        } catch (Exception e) {e.printstacktrace ();        } finally {closedb ();    } return false; }/** * Bulk operations (add, delete, change) * * @param sqls Insert SQL statement * @param objs SQL parameter (a two-dimensional array) * @retuRN */public boolean executebatch (list<string> sqls, object[][] objs) {connectdb ();            try {Conn.setautocommit (false);                for (int i = 0, size = sqls.size (); i < size; i++) {String sql = Sqls.get (i);                PS = conn.preparestatement (SQL); if (null! = NULL && NULL! = Objs[i]) {for (int j = 0, paramssize = objs[i].length; J < para Mssize;                    J + +) {Ps.setobject (j + 1, objs[i][j]);            }} ps.executeupdate ();        } conn.commit ();            } catch (Exception e) {try {conn.rollback ();            } catch (SQLException ex) {Logger.getlogger (JDBC.class.getName ()). log (Level.severe, NULL, ex);        } e.printstacktrace ();        } finally {closedb ();    } return true; }/** * Executes an INSERT statement while returning the PK at insertion * @Param SQL * @param params * @return PK */public int insertandgetpk (String sql, object[] params) {i        NT key = 0;        Connectdb ();            try {Conn.setautocommit (false);            PS = conn.preparestatement (sql, Statement.return_generated_keys);                    if (null! = params) {for (int i = 0, paramssize = params.length; i < paramssize; i++) {                Ps.setobject (i + 1, params[i]);            }} ps.executeupdate ();            ResultSet keys = Ps.getgeneratedkeys ();            if (Keys.next ()) {key = Keys.getint (1);        } conn.commit ();                } catch (Exception Exception) {try {conn.rollback ();                Exception.printstacktrace ();            return 0;            } catch (SQLException ex) {Logger.getlogger (JDBC.class.getName ()). log (Level.severe, NULL, ex); }} finally {Closedb ();    } return key; }/** * Query * * @param SQL SQL statements (parameters with "?")            * @param params parameter value * @return */public ResultSet query (String sql, object[] params) {try {            PS = conn.preparestatement (SQL);                    if (null! = params) {for (int i = 0, paramssize = params.length; i < paramssize; i++) {                Ps.setobject (i + 1, params[i]);        }} rs = Ps.executequery ();        } catch (Exception ex) {ex.printstacktrace ();    } return RS;        } public static void Main (string[] agrs) {list<string> sqls = new arraylist<string> ();        Sqls.add ("INSERT into image (Url,title) VALUES ('? ', '? ')");        Sqls.add ("INSERT into image (Url,title) VALUES (' 2 ', ' 222 ')");        Sqls.add ("INSERT into image (Url,title) VALUES (?,?)");        Sqls.add ("INSERT into image (Url,title) VALUES (?,?)"); object[][] Objs = new object[][]{{"1", "111 "}, NULL, {" 3 "," 333 "}, {" 4 "," 444 "}};        JDBC db = new JDBC ();    Db.executebatch (SQLS, NULL); }}

JDBC Tool class

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.