1. 程式人生 > >JDBC mysql 相關內容筆記

JDBC mysql 相關內容筆記

數據庫字段 tst l數據庫 lex mysql數據庫 tro exception 解決 except

解決亂碼: url字符串加上?useUnicode=true&characterEncoding=utf-8;

mysql數據庫無法插入中文數據問題:將mysql數據庫的編碼改為utf-8;

ResultSet中get(列名)方法不一定獲取的是數據庫字段名,也有可能是自定義的別名,例如:select id,name,password pwd from user 此時resultSet.get("password")會拋出異常!

反射封裝JDBC

  1 package com.jdbc;
  2 
  3 import java.lang.reflect.Field;
  4 import
java.sql.Connection; 5 import java.sql.DriverManager; 6 import java.sql.PreparedStatement; 7 import java.sql.ResultSet; 8 import java.sql.ResultSetMetaData; 9 import java.sql.SQLException; 10 import java.util.ArrayList; 11 import java.util.List; 12 13 public class TestReflectionJDBC<T> {
14 15 private static Connection connection = null; 16 17 private static ResultSet resultSet = null; 18 19 private static PreparedStatement preparedStatement = null; 20 21 public static void main(String[] args) { 22 23 } 24 25 public Connection getConnection() throws
Exception { 26 Class.forName("com.mysql.jdbc.Driver"); 27 if (connection != null) { 28 connection = DriverManager.getConnection( 29 "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", "root", "123456"); 30 } 31 return connection; 32 } 33 34 public List<T> query(String sql, Class<T> clzz, Object... obj) throws Exception { 35 List<T> list = new ArrayList<T>(); 36 preparedStatement = getConnection().prepareStatement(sql); 37 for (int i = 0; i < obj.length; i++) { 38 preparedStatement.setObject(i + 1, obj[i]); 39 } 40 resultSet = preparedStatement.executeQuery(); 41 if (resultSet != null) { 42 ResultSetMetaData resultSetMetaData = null; 43 while (resultSet.next()) { 44 if (resultSetMetaData == null) { 45 resultSetMetaData = resultSet.getMetaData(); 46 int count = resultSetMetaData.getColumnCount(); 47 T t = clzz.newInstance(); 48 for (int i = 0; i < count; i++) { 49 String name = resultSetMetaData.getColumnName(i + 1); 50 Field field = clzz.getDeclaredField(name); 51 field.setAccessible(true); 52 Object value = resultSet.getObject(name); 53 field.set(t, value); 54 } 55 list.add(t); 56 } 57 } 58 } 59 return list; 60 } 61 62 public int update(String sql, Object... obj) { 63 int result = 0; 64 try { 65 preparedStatement = getConnection().prepareStatement(sql); 66 for (int i = 0; i < obj.length; i++) { 67 preparedStatement.setObject(i + 1, obj[i]); 68 } 69 result = preparedStatement.executeUpdate(); 70 } catch (SQLException e) { 71 e.printStackTrace(); 72 } catch (Exception e) { 73 e.printStackTrace(); 74 } finally { 75 if (preparedStatement != null) { 76 try { 77 preparedStatement.close(); 78 } catch (SQLException e) { 79 e.printStackTrace(); 80 } 81 } 82 if (resultSet != null) { 83 try { 84 resultSet.close(); 85 } catch (SQLException e) { 86 e.printStackTrace(); 87 } 88 } 89 if (connection != null) { 90 try { 91 connection.close(); 92 } catch (SQLException e) { 93 e.printStackTrace(); 94 } 95 } 96 } 97 return result; 98 } 99 100 }

JDBC mysql 相關內容筆記