Get the App
SLTechnology News&Howtos  ›  Development  › 

How sqlserver and java convert records in resultSet into student objects

Shulou Source: shulou.com Published: 2022-06-02 06:36:09 10月03日 Update

This article mainly introduces sqlserver and java how to convert the records in resultSet into student objects, which has a certain reference value, and interested friends can refer to it. I hope you can learn a lot after reading this article.

To convert the result to an object, the first step is to create an object:

1.Student.java

The attributes in public class Student {/ / student number, name, class, gender, major, college / class must be the same as those in the database, including name, data type private String student number; private String name; private String class; private String gender; private String major; private String college; public String getsno () {return student number } public void setsno (String sno) {this. Student ID = sno;} public String getsex () {return gender;} public void setsex (String sex) {this. Gender = sex;} public String getName () {return name;} public void setName (String name) {this. Name = name;}}

Create a method that returns a result set

2.DBUtil.java

Import java.lang.reflect.Field;import java.sql.*;import java.text.SimpleDateFormat;import java.util.*;import java.util.Date;public class DBUtil {/ / Connect to the database static Connection getSQLConnection (String ip, String user, String pwd, String db) {Connection con = null; try {Class.forName ("net.sourceforge.jtds.jdbc.Driver") / / con = DriverManager.getConnection ("jdbc:jtds:sqlserver://" + ip + ": 1433 /" + db + "; charset=utf8", user, pwd); / / jdbc:jtds:sqlserver://localhost:1433/dbname / / resolve output Chinese garbled con = DriverManager.getConnection ("jdbc:jtds:sqlserver://" + ip + ": 1433 /" + db, user, pwd) } catch (ClassNotFoundException e) {e.printStackTrace ();} catch (SQLException e) {e.printStackTrace ();} return con } / * * convert the rs result into an object list * / public static List populate (ResultSet rs, Class classTemp) throws SQLException, InstantiationException, IllegalAccessException {/ / element object of the result set ResultSetMetaData rsmd = rs.getMetaData (); / / get the number of elements of the result set int colCount = rsmd.getColumnCount () / / list set of returned results List list = new ArrayList (); / / property array of business objects Field [] fields = classTemp.getDeclaredFields (); while (rs.next ()) {/ / operate on each record Object obj = classTemp.newInstance () / / construct a business object entity / / take out each field and assign it to for (int I = 1 position I

Tags: Result object attribute data name student number gender database article student major business element college class output consistent individual number garbled Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Xiaomi OPPO Reno Shulou Technology Linux