java sqlserver工具类_java 数据库连接工具类

数据库连接类: DBUtil

package com.elink.services;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

/**

* @author lucher

* 本类为连接各种数据库的工具类,包括sqlserver、mysql、oracle的连接,以及关闭连接方法

* 该类一般配合SQLUtil使用

*/

public class DBUtil {

// sqlserver 驱动

private static final String SQLSERVER_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

// 数据库地址url 前面的为固定写法,后面的分别为ip地址:端口号,数据库名

//private static final String SQLSERVER_URL = "jdbc:microsoft:sqlserver://localhost:1433;databaseName=WM"; //用微软的jar包(3个)的情况

private static final String SQLSERVER_URL = "jdbc:sqlserver://127.0.0.1:1433;databaseName=NewMedicineDatabase"; //用普通jar包(1个)的时候

private static final String SQLSERVER_USERNAME = "sa";// sqlserver 数据库用户名

private static final String SQLSERVER_PASSWORD = "1qazxsw2";// sqlserver 数据库密码

/**

* 获取SQLSERVER数据库连接

* @return 数据库的连接

*/

public static Connection getSQLSERVERConnection() {

Connection conn = null;

try {

//自动创建驱动程序的实例且自动调用DriverManager来注册它

Class.forName(SQLSERVER_DRIVER);

conn = DriverManager.getConnection(SQLSERVER_URL, SQLSERVER_USERNAME, SQLSERVER_PASSWORD);

System.out.println(conn);

} catch (ClassNotFoundException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return conn;

}

// mysql 驱动

private static final String MYSQL_DRIVER = "com.mysql.jdbc.Driver";

// 数据库地址url 前面的为固定写法,后面的分别为ip地址:端口号,数据库名

private static final String MYSQL_URL = "jdbc:mysql://localhost:3306/dossier";

private static final String MYSQL_USERNAME = "admin";// mysql 数据库用户名

private static final String MYSQL_PASSWORD = "admin";// mysql 数据库密码

/**

* 获取MYSQL数据库连接

* @return 数据库的连接

*/

public static Connection getMYSQLConnection() {

Connection conn = null;

try {

//自动创建驱动程序的实例且自动调用DriverManager来注册它

Class.forName(MYSQL_DRIVER);

conn = DriverManager.getConnection(MYSQL_URL, MYSQL_USERNAME, MYSQL_PASSWORD);

} catch (ClassNotFoundException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return conn;

}

// oracle驱动

private static final String ORACLE_DRIVER = "oracle.jdbc.driver.OracleDriver";

// 数据库地址url 前面的为固定写法,后面的分别为ip地址:端口号,数据库名

private static final String ORACLE_URL = "jdbc:oracle:thin:@localhost:1521:dababase";

private static final String ORACLE_USERNAME = "admin";// oracle 数据库用户名

private static final String ORACLE_PASSWORD = "admin";// oracle 数据库密码

/**

* 获取ORACLE数据库连接

* @return 数据库的连接

*/

public static Connection getORACLEConnection() {

Connection conn = null;

try {

//自动创建驱动程序的实例且自动调用DriverManager来注册它

Class.forName(ORACLE_DRIVER);

conn = DriverManager.getConnection(ORACLE_URL, ORACLE_USERNAME, ORACLE_PASSWORD);

} catch (ClassNotFoundException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return conn;

}

/**

* 关闭数据库连接,针对有参数的查询情况

* @param rs 返回的查询结果

* @param pstmt

* @param conn

*/

public static void closeConn(ResultSet rs, PreparedStatement pstmt, Connection conn) {

if (rs != null) {

try {

rs.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

if (pstmt != null) {

try {

pstmt.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

if (conn != null) {

try {

conn.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

/**

* 关闭数据库连接重载,针对没有参数的查询情况

* @param rs

* @param ps

* @param conn

*/

public static void closeConn(ResultSet rs, Statement ps, Connection conn) {

if (rs != null) {

try {

rs.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

if (ps != null) {

try {

ps.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

if (conn != null) {

try {

conn.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

/**

* 关闭数据库连接重载,针对更新语句情况

* @param pstmt

* @param conn

*/

public static void closeConn(PreparedStatement pstmt, Connection conn) {

if (pstmt != null) {

try {

pstmt.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

if (conn != null) {

try {

conn.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

/**

* 关闭数据库连接重载,针对同时执行两条条更新语句

* @param pstmt1

* @param pstmt2

* @param conn

*/

public static void closeConn(PreparedStatement pstmt1, PreparedStatement pstmt2, Connection conn) {

if (pstmt1 != null) {

try {

pstmt1.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

if (pstmt2 != null) {

try {

pstmt2.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

if (conn != null) {

try {

conn.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}

SQL语句类: SQLUtil

package util;

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;

/**

* @author lucher

* 本类为sql工具类,包括sql无参、有参查询,以及sql更新语句方法

* 该类一般配合DBUtil使用,只是列举了常用的方法,具体使用时稍加修改

*/

public class SQLUtil {

// 无参数的查询语句

private static final String sql1 = "select * from company";

// 有参数的查询语句

private static final String sql2 = "select password from company where name=?";

// 更新语句

private static final String sql3 = "update company set password=? where name=?";

// 删除语句,同时执行

private static final String sql4 = "delete from user where id=?";

private static final String sql5 = "delete from userInfo where id=?";

/**

* 无参数查询,返回类型据情况稍加修改,以sqlserver为例,其他类似

*

* @return 所有记录的名字的list

*/

public static List getAll() {

Connection conn = null;

Statement ps = null;

ResultSet rs = null;

List info = new ArrayList();

try {

conn = DBUtil.getSQLSERVERConnection();

ps = conn.createStatement();

rs = ps.executeQuery(sql1);

while (rs.next()) {

info.add(rs.getString("name")); // 根据具体情况定

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

DBUtil.closeConn(rs, ps, conn);

}

return info;

}

/**

* 有参数查询,返回类型据情况稍加修改,以sqlserver为例,其他类似

*

* @param name

* @param password

* @return 返回指定名字和密码的记录list

*/

public static List getAllByNP(String name, String password) {

Connection conn = null;

PreparedStatement pstmt = null;

ResultSet rs = null;

List info = new ArrayList();

try {

conn = DBUtil.getSQLSERVERConnection();

pstmt = conn.prepareStatement(sql1);

pstmt.setString(1, name);

pstmt.setString(2, password);

rs = pstmt.executeQuery();

while (rs.next()) {

info.add(rs.getString(1));

info.add(rs.getString(2));

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

DBUtil.closeConn(rs, pstmt, conn);

}

return info;

}

/**

* 更新类方法,只执行一条的情况,以sqlserver为例,其他类似

* @param name

* @param password

* @return 执行更新的结果

*/

public static boolean updatePasswordByName(String name, String password) {

int result = 0;

boolean flag = true;

Connection conn = null;

PreparedStatement pstmt = null;

try {

conn = DBUtil.getSQLSERVERConnection();

pstmt = conn.prepareStatement(sql3);

pstmt.setString(1, password);

pstmt.setString(2, name);

result = pstmt.executeUpdate();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

DBUtil.closeConn(pstmt, conn);

}

if (result == 0) {

flag = false;

}

return flag;

}

/**

* 更新类方法,同时执行两条的情况,以sqlserver为例,其他类似

* @param id

* @return 执行删除的结果

*/

public static boolean deleteById(int id) {

int result1 = 0;

int result2 = 0;

boolean flag = true;

Connection conn = null;

PreparedStatement pstmt1 = null;

PreparedStatement pstmt2 = null;

try {

conn = DBUtil.getSQLSERVERConnection();

conn.setAutoCommit(false);

pstmt1 = conn.prepareStatement(sql4);

pstmt1.setInt(1, id);

pstmt2 = conn.prepareStatement(sql5);

pstmt2.setInt(1, id);

result1 = pstmt1.executeUpdate();

result2 = pstmt2.executeUpdate();

conn.commit();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

try {

conn.rollback();

} catch (SQLException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

} finally {

DBUtil.closeConn(pstmt1, pstmt2, conn);

}

if (result1 == 0 || result2 == 0) {

flag = false;

}

return flag;

}

}

package com.hexiang.utils; import java.sql.*; import java.util.*; /** * * Title: 数据库工具类 * * * Description: 将大部分的数据库操作放入这个类中, 包括数据库连接的建立, 自动释放等. * * * @author beansoft 日期: 2004年04月 * @version 2.0 */ public class DatabaseUtil { /** 数据库连接 */ private java.sql.Connection connection; /** * All database resources created by this class, should be free after all * operations, holds: ResultSet, Statement, PreparedStatement, etc. */ private ArrayList resourcesList = new ArrayList(5); public DatabaseUtil() { } /** 关闭数据库连接并释放所有数据库资源 */ public void close() { closeAllResources(); close(getConnection()); } /** * Close given connection. * * @param connection * Connection */ public static void close(Connection connection) { try { connection.close(); } catch (Exception ex) { System.err.println("Exception when close a connection: " + ex.getMessage()); } } /** * Close all resources created by this class. */ public void closeAllResources() { for (int i = 0; i < this.getResourcesList().size(); i++) { closeJDBCResource(getResourcesList().get(i)); } } /** * Close a jdbc resource, such as ResultSet, Statement, Connection.... All * these objects must have a method signature is void close(). * * @param resource - * jdbc resouce to close */ public void closeJDBCResource(Object resource) { try { Class clazz = resource.getClass(); java.lang.reflect.Method method = clazz.getMethod("close", null); method.invoke(resource, null); } catch (Exception e) { // e.printStackTrace(); } } /** * 执行 SELECT 等 SQL 语句并返回结果集. * * @param sql * 需要发送到数据库 SQL 语句 * @return a ResultSet object that contains the data produced * by the given query; never null */ public ResultSet executeQuery(String sql) { try { Statement statement = getStatement(); ResultSet rs = statement.executeQuery(sql); this.getResourcesList().add(rs); this.getResourcesList().add(statement);// BUG fix at 2006-04-29 by BeanSoft, added this to res list // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); return rs; } catch (Exception ex) { System.out.println("Error in executeQuery(\"" + sql + "\"):" + ex); // ex.printStackTrace(); return null; } } /** * Executes the given SQL statement, which may be an INSERT, * UPDATE, or DELETE statement or an SQL * statement that returns nothing, such as an SQL DDL statement. 执行给定的 SQL * 语句, 这些语句可能是 INSERT, UPDATE 或者 DELETE 语句, 或者是一个不返回任何东西的 SQL 语句, 例如一个 SQL * DDL 语句. * * @param sql * an SQL INSERT,UPDATE or * DELETE statement or an SQL statement that * returns nothing * @return either the row count for INSERT, * UPDATE or DELETE statements, or * 0 for SQL statements that return nothing */ public int executeUpdate(String sql) { try { Statement statement = getStatement(); return statement.executeUpdate(sql); // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); } catch (Exception ex) { System.out.println("Error in executeUpdate(): " + sql + " " + ex); //System.out.println("executeUpdate:" + sql); ex.printStackTrace(); } return -1; } /** * 返回记录总数, 使用方法: getAllCount("SELECT count(ID) from tableName") 2004-06-09 * 可滚动的 Statement 不能执行 SELECT MAX(ID) 之类的查询语句(SQLServer 2000) * * @param sql * 需要执行的 SQL * @return 记录总数 */ public int getAllCount(String sql) { try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); ResultSet rs = statement.executeQuery(sql); rs.next(); int cnt = rs.getInt(1); rs.close(); try { statement.close(); this.getResourcesList().remove(statement); } catch (Exception ex) { ex.printStackTrace(); } return cnt; } catch (Exception ex) { System.out.println("Exception in DatabaseUtil.getAllCount(" + sql + "):" + ex); ex.printStackTrace(); return 0; } } /** * 返回当前数据库连接. */ public java.sql.Connection getConnection() { return connection; } /** * 连接新的数据库对象到这个工具类, 首先尝试关闭老连接. */ public void setConnection(java.sql.Connection connection) { if (this.connection != null) { try { getConnection().close(); } catch (Exception ex) { } } this.connection = connection; } /** * Create a common statement from the database connection and return it. * * @return Statement */ public Statement getStatement() { // 首先尝试获取可滚动的 Statement, 然后才是普通 Statement Statement updatableStmt = getUpdatableStatement(); if (updatableStmt != null) return updatableStmt; try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getStatement(): " + ex); } return null; } /** * Create a updatable and scrollable statement from the database connection * and return it. * * @return Statement */ public Statement getUpdatableStatement() { try { Statement statement = getConnection() .createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getUpdatableStatement(): " + ex); } return null; } /** * Create a prepared statement and return it. * * @param sql * String SQL to prepare * @throws SQLException * any database exception * @return PreparedStatement the prepared statement */ public PreparedStatement getPreparedStatement(String sql) throws SQLException { try { PreparedStatement preparedStatement = getConnection() .prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(preparedStatement); return preparedStatement; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Return the resources list of this class. * * @return ArrayList the resources list */ public ArrayList getResourcesList() { return resourcesList; } /** * Fetch a string from the result set, and avoid return a null string. * * @param rs * the ResultSet * @param columnName * the column name * @return the fetched string */ public static String getString(ResultSet rs, String columnName) { try { String result = rs.getString(columnName); if (result == null) { result = ""; } return result; } catch (Exception ex) { } return ""; } /** * Get all the column labels * * @param resultSet * ResultSet * @return String[] */ public static String[] getColumns(ResultSet resultSet) { if (resultSet == null) { return null; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); if (numberOfColumns <= 0) { return null; } String[] columns = new String[numberOfColumns]; //System.err.println("numberOfColumns=" + numberOfColumns); // Get the column names for (int column = 0; column < numberOfColumns; column++) { // System.out.print(metaData.getColumnLabel(column + 1) + "\t"); columns[column] = metaData.getColumnName(column + 1); } return columns; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Get the row count of the result set. * * @param resultset * ResultSet * @throws SQLException * if a database access error occurs or the result set type is * TYPE_FORWARD_ONLY * @return int the row count * @since 1.2 */ public static int getRowCount(ResultSet resultset) throws SQLException { int row = 0; try { int currentRow = resultset.getRow(); // Remember old row position resultset.last(); row = resultset.getRow(); if (currentRow > 0) { resultset.absolute(row); } } catch (Exception ex) { ex.printStackTrace(); } return row; } /** * Get the column count of the result set. * * @param resultSet * ResultSet * @return int the column count */ public static int getColumnCount(ResultSet resultSet) { if (resultSet == null) { return 0; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); return numberOfColumns; } catch (Exception ex) { ex.printStackTrace(); } return 0; } /** * Read one row's data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * @param resultSet * ResultSet * @return Hashtable */ public static final Hashtable readResultToHashtable(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { resultHash.put(columns[i], getString(resultSet, columns[i])); } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** * Read data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * Note: assume the default database string encoding is ISO8859-1. * * @param resultSet * ResultSet * @return Hashtable */ @SuppressWarnings("unchecked") public static final Hashtable readResultToHashtableISO(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { String isoString = getString(resultSet, columns[i]); try { resultHash.put(columns[i], new String(isoString .getBytes("ISO8859-1"), "GBK")); } catch (Exception ex) { resultHash.put(columns[i], isoString); } } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** Test this class. */ public static void main(String[] args) throws Exception { DatabaseUtil util = new DatabaseUtil(); // TODO: 从连接池工厂获取连接 // util.setConnection(ConnectionFactory.getConnection()); ResultSet rs = util.executeQuery("SELECT * FROM e_hyx_trans_info"); while (rs.next()) { Hashtable hash = readResultToHashtableISO(rs); Enumeration keys = hash.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); System.out.println(key + "=" + hash.get(key)); } } rs.close(); util.close(); } }
package com.hexiang.utils; /** * SQLUtils utils = new SQLUtils(User.class); utils.setWhereStr("", "id", "=", 100).setWhereStr("and", "name", " ", "is null").setWhereStr("and", "date", ">=", new Date()); utils.setOrderByStr("id", "desc").setOrderByStr("name", "asc"); System.out.println(utils.buildSelectSQL()); System.out.println(utils.buildCountSQL()); */ import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class SqlUtils { private String beanName; private String beanShortName; private Map propertyMap; private List conditionList; private List relationList; private Map orderByMap; public SqlUtils(Class instance) { this.setBeanName(instance.getSimpleName()); this.setBeanShortName(Character.toLowerCase(this.getBeanName() .charAt(0)) + ""); init(); } public SqlUtils() { init(); } void init(){ propertyMap = new LinkedHashMap(); conditionList = new LinkedList(); relationList = new LinkedList(); orderByMap = new LinkedHashMap(); } /** * 添加查询条件 * * @param relation * 关联 "and","or"等 * @param property * 查询的对象属性 * @param condition * 查询的条件,关系符 * @param value * 查询的值 */ public SqlUtils setWhereStr(String relation, String property, String condition, Object value) { if(value != null){ relationList.add(relation); propertyMap.put(property, value); conditionList.add(condition); } return this; } private String buildWhereStr() { StringBuffer buffer = new StringBuffer(); if (!propertyMap.isEmpty() && propertyMap.size() > 0) { buffer.append("WHERE 1 = 1 "); int index = 0; for (String property : propertyMap.keySet()) { if (property != null && !property.equals("")) { buffer.append(r
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值