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 = resultset.getMetaData();
		int col_len = metaData.getColumnCount();
		while (resultset.next()) {
			for (int i = 0; i < col_len; i++) {
				String col_name = metaData.getColumnName(i + 1);
				Object col_values = resultset.getObject(col_name);
				if (col_values == null) {
					col_values = "";
				}
				map.put(col_name, col_values);
			}
		}
		return map;
	}

	/**
	 * 查找多条记录
	 *
	 * @return
	 */

	public List<Map<String, Object>> findMoreResultString(String sql,
			List<Object> params) throws SQLException {
		List<Map<String, Object>> list = new ArrayList<Map<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 = resultset.getMetaData();
		int col_len = metaData.getColumnCount();
		while (resultset.next()) {
			Map<String, Object> map = new HashMap<String, Object>();
			for (int i = 0; i < col_len; i++) {
				String col_name = metaData.getColumnName(i + 1);
				Object col_values = resultset.getObject(col_name);
				if (col_values == null) {
					col_values = "";
				}
				map.put(col_name, col_values);
			}

			list.add(map);
		}

		return list;
	}

	// 利用反射机制
	/**
	 * 通过反射机制访问数据库
	 *
	 * @param sql
	 * @param params
	 * @param cls
	 * @return
	 * @throws SQLException
	 * @throws Exception
	 * @throws IllegalAccessException
	 */
	public <T> List<T> findMore(String sql, List<Object> params, Class<T> cls)
			throws SQLException, Exception {
		List<T> list = new ArrayList<T>();
		int index = 1;
		Object resultObject=null;
		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 = resultset.getMetaData();
		int col_len = metaData.getColumnCount();
		while (resultset.next()) {
			resultObject = cls.newInstance();
			for (int i = 0; i < col_len; i++) {
				String col_name = metaData.getColumnName(i+1);
				Object col_values = resultset.getObject(col_name);
				if (col_values == null) {
					col_values = "";
				}
				Field field = cls.getDeclaredField(col_name);
				field.setAccessible(true);
				field.set(resultObject, col_values);
			}
			list.add((T) resultObject);
		}

		return list;
	}

	/**
	 * 关闭数据库连接
	 */
	public void releaseConnection() {

		if (resultset != null)
			try {
				resultset.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		if (preparedStatement != null)
			try {
				preparedStatement.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		if (connection != null)
			try {
				connection.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}

	/**
	 *
	 * @param args
	 * @throws SQLException
	 */
	public static void main(String[] args) throws SQLException {
		JDBCUtils jdbcUtils = new JDBCUtils();
		jdbcUtils.getConnection();

		/*
		 * String sql = "insert into userinfo(username,pwd) values (?,?)";
		 * List<Object> params = new ArrayList<Object>(); params.add("admin");
		 * params.add("admin"); boolean flag =
		 * jdbcUtils.updateByPrepareStatement(sql, params);
		 * System.out.println(flag);
		 */
		String sql = "select * from userinfo where id=?";
		String sql1 = "select * from userinfo";
		List<Object> params = new ArrayList<Object>();
		/*params.add(1);
		Map map = jdbcUtils.findSimpleResult(sql, params);

		try {
			List list = jdbcUtils.findMoreResultString(sql1, null);
			System.out.println(map);
			System.out.println(list);
		}

		catch (Exception e) {
			e.printStackTrace();
		} finally {
			jdbcUtils.releaseConnection();
		}*/
		try {
			System.out.println("---fsdfas");
		List<userinfo> userlist=	jdbcUtils.findMore(sql1, null, userinfo.class);
		System.out.println("---"+userlist);
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			jdbcUtils.releaseConnection();
		}
	}
}

androidj常用数据库操作JDBC Utils

时间: 2024-10-15 01:18:14

androidj常用数据库操作JDBC Utils的相关文章

常用数据库的JDBC 的URL形式

常用数据库的JDBC 的URL形式: *SQL Servler 2000 jdbc:microsoft:sqlserver://localhost:1433;databasename=pubs *Oracle jdbc:oracle:thin:@localhost:1521;ORCL *MySQL jdbc:mysql://localhost:3306/databasename 另外还可以通过JDBC-ODBC桥的方式访问数据库,这种形式加载的驱动程序类是: sun.jdbc.odbc.Jdbc

Mysql 常用数据库操作

一.数据库操作: 1.查看数据库: >SHOW DATABASES; 2.创建数据库: >CREATE DATABASE db_name; //db_name为数据库名 3.使用数据库: >USE db_name; 4.删除数据库: >DROP DATABASE db_name; 二.创建表: 1.创建表: >CREATE TABLE table_name( >id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT, //id值,无符号.

第20章 数据库操作----JDBC概述

JDBC是一种可用于执行SQL语句的Java API(Application Programming Interface,应用程序设计接口),是连接数据库和Java应用程序的纽带. 1.JDBC-ODBC桥 JDBC-ODBC桥是一个JDBC驱动程序,完成了从JDBC操作到ODBC操作之间的转换工作,允许JDBC驱动程序被用作ODBC的驱动程序.使用JDBC-ODBC桥连接数据库的步骤如下: (1)首先加载JDBC-ODBC桥的驱动程序,代码如下: Class.forName(“sun.jdbc

[转]YII2 常用数据库操作

1.对象操作: //1.简单查询 $admin=Admin::model()->findAll($condition,$params); $admin=Admin::model()->findAll("username=:name",array(":name"=>$username)); $infoArr= NewsList::model()->findAll("status = '1' ORDER BY id DESC limit

常用数据库操作

1 .sqlite 下载地址:https://www.sqlite.org/download.html Precompiled Binaries for Windows下下载 : sqlite-tools-win32-x86-3240000.zip(1.64 MiB) sqlite-dll-win64-x64-3240000.zip(736.78 KiB) 解压这两个文件,然后将这三个exe,1个dll,1个def文件都放到system32下,就完成安装了 常用命令: sqlite3 命令行进入

常用数据库操作(一)

1.sp_helptext: 显示规则,默认值,为加密的存储过程,用户定义函数,触发器或视图 2.根据字段名查询数据库中的某表名 select [name] from sysobjects where [id] in (select[id] from syscolumns where [name] = '字段名') 3. Arithmetic overflow error converting numeric to data type numeric 添加数据时出现异常,截图如下: 提示说,数据

mongoose 常用数据库操作 插入

项目 db.js var mongoose = require('mongoose'); mongoose.connect('mongodb://127.0.0.1:27017/whhhh', { useMongoClient: true }); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function (call

mongoose 常用数据库操作 查询

条件查询 Model.find(conditions, [fields], [options], [callback]) demo1 try.js var User = require("./user.js"); function getByConditions(){ var wherestr = {'username' : 'xiaoming'}; User.find(wherestr, function(err, res){ if (err) { console.log("

常用数据库操作语句(1)

建库CREATE DATABASE IF NOT EXISTS gloryroad DEFAULT CHARSET utf8 COLLATE utf8_general_ci;建表create table studentInfo(ID int not null auto_increment comment "不为空的自增长的主键ID",student_id varchar(20) not null,name varchar(30) not null,sex char(4),tel var