is to use JDBC to fetch data from the database and return it as a Java object

Source: Internet
Author: User

/** * * @param c * For example Person.class * @param primarykeys * Primarykeys primary key, parameter order and table consistency if ID, The name of the primary key class is GetEntity (person.class,1, "name") * @return */public Static object GetEntity (Class C, object ... prima Rykeys) {PreparedStatement PS = null; ResultSet rs = null;databasemetadata DMD = Null;object obj = null;//the object to return string tableName = C.getsimplename (). Tolowercas E ();//The name of the person table list primarykeynamelist = new ArrayList (); field[] fields = C.getfields ();//Get all the properties StringBuilder sql = new StringBuilder ("SELECT * from" + tablename+ "where"); tr y {obj = c.newinstance ();d MD = getconnection (). GetMetaData (); rs = Dmd.getprimarykeys (null, NULL, tableName); while ( Rs.next ()) {Sql.append (Rs.getobject (4) + "=?"); Sql.append ("and");p Rimarykeynamelist.add (Rs.getobject (4));//The primary key field obtained from the table is stored in the list, and the primary key is located in the table in the first few columns =rs.getstring (5)} Sql.delete (Sql.length ()-4, Sql.length ());p s = (PreparedStatement) getconnection (). Preparestatement (Sql.toString ()) ; for (int l = 0; l < PRImarykeynamelist.size (); l++) {Ps.setobject (L + 1, primarykeys[l]);} rs = Ps.executequery (); System.out.println (Ps.tostring (). Split (":") [1]); if (Rs.next ()) {for (int k = 0; K < Fields.length; k++) {fields[k].set (obj, rs.getobject (k + 1));}} Rs.close ();p s.close (); rs=null;ps=null;} catch (Exception e) {e.printstacktrace ();} finally {}return obj;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.