本文共 927 字,大约阅读时间需要 3 分钟。
java.lang.NoSuchFieldException: img_path at java.lang.Class.getDeclaredField(Class.java:2070) at com.atguigu.preparedStatement.crud.BookForQuery.queryForBook(BookForQuery.java:81) at com.atguigu.preparedStatement.crud.BookForQuery.testQueryForBook(BookForQuery.java:50) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498)
找不到此字段,主要是数据库表字段和java类属性的不匹配导致的问题,一般Java类的属性都是驼峰命名,但是字段名有可能带下划线,我们在用反射获取该结果集的字段名时候,就会因为找不到相对应的字段而报错,即ResultSetMetaData类取列的字段名的时候:
//要写成rsmd.getColumnLabel(i + 1);//不要rsmd.getColumnName(i + 1);
学过mysql的都知道可以取别名,即给sql语句取和Java类属性名一样的别名,如果没有别名getColumnLabel方法会默认取原来的字段名
String sql = "select id, name, price, author, sales, stock, img_path as imgPath from t_book where id = ?";
转载地址:http://pakqf.baihongyu.com/