首页 > 代码库 > androidj常用数据库操作JDBC Utils

androidj常用数据库操作JDBC Utils

package mypackage;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JDBCUtils {

	private final String USERNAME = "root";
	private final String PWD = "admin";
	private final String DRIVER = "com.mysql.jdbc.Driver";
	private Connection connection;
	private java.sql.PreparedStatement preparedStatement;
	private ResultSet resultset;
	private String URL = "jdbc:mysql://localhost:3306/mydb";

	public JDBCUtils() {
		try {
			Class.forName(DRIVER);
			System.out.println("注册驱动成功");
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	// 定义获得数据库的链接

	public Connection getConnection() {
		try {
			connection = DriverManager.getConnection(URL, USERNAME, PWD);

		} catch (Exception e) {
			// TODO: handle exception
		}
		return connection;
	}

	/**
	 * 
	 * @param sql
	 * @param params
	 * @return
	 * @throws SQLException
	 */
	public boolean updateByPrepareStatement(String sql, List<Object> params)
			throws SQLException {
		boolean flag = false;
		int result = -1;// 受影响的行数
		int index = 1;
		preparedStatement = connection.prepareStatement(sql);
		if (params != null && !params.isEmpty()) {
			for (int i = 0; i < params.size(); i++) {
				preparedStatement.setObject(index++, params.get(i));
			}
		}
		result = preparedStatement.executeUpdate();
		flag = result > 0 ? true : false;
		return flag;
	}

	/**
	 * 查询返回单条记录
	 * 
	 * @param sql
	 * @param params
	 * @return
	 * @throws SQLException
	 */
	public Map<String, Object> findSimpleResult(String sql, List<Object> params)
			throws SQLException {
		Map<String, Object> map = new HashMap<String, Object>();
		int index = 1;
		preparedStatement = connection.prepareStatement(sql);
		if (params != null && !params.isEmpty()) {
			for (int i = 0; i < params.size(); i++) {
				preparedStatement.setObject(index++, params.get(i));
			}
		}
		resultset = preparedStatement.executeQuery();// 返回查询结果
		ResultSetMetaData metaData = http://www.mamicode.com/resultset.getMetaData();>