標籤:java jdbc
</pre><p>使用反射 來操作 這裡是練習反射的使用</p><p>連結資料庫工具類</p><p><pre name="code" class="java">private static final String DRIVER = "com.mysql.jdbc.Driver";private static final String USER = "root";private static final String PW = "1234";private static final String URL="jdbc:mysql://localhost:3306/reflction";/** * 連結資料庫 * @return */public static Connection getConnection(){try {Class.forName(DRIVER);Connection con = DriverManager.getConnection(URL, USER, PW);System.out.println("Connection OK .....");return con;} catch (Exception e) {System.out.println("Connection error...");e.printStackTrace();}return null;}
核心類
public Object getById(Class clazz, Integer id) throws Exception{Object obj = clazz.newInstance();//實列一個//建立連結Connection con = JdbcUtils.getConnection();//擷取實體的名字 需要拼接 從最後一個點開始String tablename = clazz.getName().substring(clazz.getName().lastIndexOf("."));//拼接sql 語句String sql = "select * from "+tablename+" where id=?";try {PreparedStatement psmt = con.prepareStatement(sql);psmt.setInt(1, id);//查到結果集ResultSet rs = psmt.executeQuery();//遍曆結果while(rs.next()){//得到所有屬性Field[] fields = clazz.getDeclaredFields();for (Field field : fields) {//遍曆屬性//擷取屬性名稱 String fname = field.getName();//擷取屬性類型 intClass type = field.getType();//Method rsGetMethod = ResultSet.class.getMethod("getObject", String.class);Object value = rsGetMethod.invoke(rs, fname);//更改修飾符許可權field.setAccessible(true);field.set(obj, value);}
Java反射_JDBC操作資料