- 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();
- }
- }
- }
JDBC连接数据库的经典案例
最新推荐文章于 2022-10-23 19:18:06 发布