jdbc-mysql的經典案例,jdbc-mysql經典案例

來源:互聯網
上載者:User

jdbc-mysql的經典案例,jdbc-mysql經典案例

package com.execlExport.util;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;/** * DatabaseUtil  * 建立人: TanLiu * 時間: 2015-1-19 下午9:08:23 * 作用:  */public class DatabaseUtil {private final String Driver = "com.mysql.jdbc.Driver";private final String URL = "jdbc:mysql://localhost:3306/tmdest";private final String User = "root";private final String pwd ="123456";private Connection con = null;private PreparedStatement ps = null;    public ResultSet rs=null;        /**     *作用:擷取對資料庫的串連     */    public void getConnection(){        try {Class.forName(Driver);con=DriverManager.getConnection(URL,User,pwd);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}           }    /**     *作用:對資料的查詢操作     * @param sql     * @param arr     * @return 返回一個資料集rs     */    public ResultSet getQuery(String sql,String[] arr){    getConnection();    try {ps=con.prepareStatement(sql);if(arr!=null&&arr.length>0){for(int i=0;i<arr.length;i++){ps.setString(i+1, arr[i]);}}rs=ps.executeQuery();} catch (SQLException e) {e.printStackTrace();}    return rs;    }        /**     *作用:用於對資料庫的更新操作     * @param sql     * @param arr     * @return row     */    public int getUpdate(String sql,String[] arr){    int row=0;    getConnection();    try {ps=con.prepareStatement(sql);if(arr!=null&&arr.length>0){for(int i=0;i<arr.length;i++){ps.setString(i+1, arr[i]);}}row=ps.executeUpdate();} catch (SQLException e) {e.printStackTrace();}finally{this.closeAll();}        return row;    }        /**     *作用:對數庫操作的關閉     */    public void closeAll(){        try {    if(rs!=null){rs.close();    }    if(ps!=null){    ps.close();    }    if(con!=null){    con.close();    }} catch (SQLException e) {e.printStackTrace();}    }}

相關文章

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.