jdbc 链接数据库工具类

来源:互联网 发布:爱家市场网络不稳定 编辑:程序博客网 时间:2024/06/06 02:37
package com.util;import java.io.IOException;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;/** * jdbc 链接数据库工具类 * @author Administrator * */public class DBUtils {private static Properties props = new Properties();static{InputStream is = null;is = DBUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");try {props.load(is);} catch (IOException e) {e.printStackTrace();} finally{if(is!=null){try {is.close();} catch (IOException e) {e.printStackTrace();}}}}/*** 获得连接* @return conn*/public static Connection createConn(){Connection conn = null; try {Class.forName((String)props.get("driver"));//ip地址 + 数据库名称conn = DriverManager.getConnection((String)props.get("url"),(String)props.get("username"), (String)props.get("password"));} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}return conn;}/*** 编译执行* */public static PreparedStatement getPs(Connection conn , String sql){PreparedStatement ps = null; try {ps = conn.prepareStatement(sql);} catch (SQLException e) {e.printStackTrace();}return ps ; }  /**   * 关闭连接   * @param conn   */public static void close(Connection conn){if(conn != null){try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}public static void close(ResultSet rs){if(rs != null){try {rs.close();} catch (SQLException e) {e.printStackTrace();}}}public static void close(PreparedStatement ps){if(ps != null){try {ps.close();} catch (SQLException e) {e.printStackTrace();}}}}
0 0
原创粉丝点击