解决乱码: url 字符串加上? useUnicode=true&characterEncoding=utf-8;
MySQL 数据库无法插入中文数据问题: 将 MySQL 数据库的编码改为 utf-8;
ResultSet 中 get(列名) 方法不一定获取的是数据库字段名, 也有可能是自定义的别名, 例如: select id,name,password pwd from user 此时 resultSet.get("password") 会抛出异常!
反射封装 JDBC:
- package com.jdbc;
- import java.lang.reflect.Field;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.ResultSetMetaData;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.List;
- public class TestReflectionJDBC<T> {
- private static Connection connection = null;
- private static ResultSet resultSet = null;
- private static PreparedStatement preparedStatement = null;
- public static void main(String[] args) {
- }
- public Connection getConnection() throws Exception {
- Class.forName("com.mysql.jdbc.Driver");
- if (connection != null) {
- connection = DriverManager.getConnection(
- "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", "root", "123456");
- }
- return connection;
- }
- public List<T> query(String sql, Class<T> clzz, Object... obj) throws Exception {
- List<T> list = new ArrayList<T>();
- preparedStatement = getConnection().prepareStatement(sql);
- for (int i = 0; i < obj.length; i++) {
- preparedStatement.setObject(i + 1, obj[i]);
- }
- resultSet = preparedStatement.executeQuery();
- if (resultSet != null) {
- ResultSetMetaData resultSetMetaData = null;
- while (resultSet.next()) {
- if (resultSetMetaData == null) {
- resultSetMetaData = resultSet.getMetaData();
- int count = resultSetMetaData.getColumnCount();
- T t = clzz.newInstance();
- for (int i = 0; i < count; i++) {
- String name = resultSetMetaData.getColumnName(i + 1);
- Field field = clzz.getDeclaredField(name);
- field.setAccessible(true);
- Object value = resultSet.getObject(name);
- field.set(t, value);
- }
- list.add(t);
- }
- }
- }
- return list;
- }
- public int update(String sql, Object... obj) {
- int result = 0;
- try {
- preparedStatement = getConnection().prepareStatement(sql);
- for (int i = 0; i < obj.length; i++) {
- preparedStatement.setObject(i + 1, obj[i]);
- }
- result = preparedStatement.executeUpdate();
- } catch (SQLException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (preparedStatement != null) {
- try {
- preparedStatement.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- if (resultSet != null) {
- try {
- resultSet.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- if (connection != null) {
- try {
- connection.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
- return result;
- }
- }
来源: http://www.bubuko.com/infodetail-2964784.html