JDBC工具类

来源:互联网 发布:股票乖离率软件 编辑:程序博客网 时间:2024/06/15 20:31

package com.excel;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


/**

 * 数据库链接
 * @author wangjun
 *
 */
public class DBhepler {


String driver = "com.mysql.jdbc.Driver";
 //   String url = "jdbc:mysql://172.16.168.8:3306/oss3.0";
String url = "jdbc:mysql://127.0.0.1:3306/oss3.0";
   
    
    Connection con = null;
    ResultSet res = null;


    public void DataBase() {
            try {
                Class.forName(driver);
//                con = DriverManager.getConnection(url, "root", "new_pass");
                con = DriverManager.getConnection(url, "root", "root");
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                  System.err.println("装载 JDBC/ODBC 驱动程序失败。" );  
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                System.err.println("无法连接数据库" ); 
                e.printStackTrace();
            }
    }


    // 查询
    public ResultSet  Search(String sql, String str[]) {
        DataBase();
        try {
            PreparedStatement pst =con.prepareStatement(sql);
            if (str != null) {
                for (int i = 0; i < str.length; i++) {
                    pst.setString(i + 1, str[i]);
                }
            }
            res = pst.executeQuery();


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return res;
    }


    // 增删修改
    public int AddU(String sql, String str[]) {
        int a = 0;
        DataBase();
        try {
            PreparedStatement pst = con.prepareStatement(sql);
            if (str != null) {
                for (int i = 0; i < str.length; i++) {
                    pst.setString(i + 1, str[i]);
                }
            }
            a = pst.executeUpdate();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return a;
    }
}