简体   繁体   中英

Save Array From Dao Class in Java

How can I access ename array of string from Employee to EmployeeDao . I want to save the value with a for loop like st.setString(1,ename[l]) . If I write an EmployeeSave() method in the bean class there is no problem, but I want to write it in EmployeeDao

st.setString(1, E.getEname()) 

give me error as the method setString(int, String) in the type PreparedStatement is not applicable for the arguments (int, String[]).

Employee.class

package com;

public class Employee {

    public String[] getEname() {
        return ename;
    }

    public void setEname(String[] ename) {
        this.ename = ename;
    }

    private String ename[];

}

EmployeeDao.class

package com;
import java.sql.*;
public class EmployeeDao {

    public static void SaveEmployee(Employee E) {
        Connection con = null;
        String sql = "";

        try 
        {
            PreparedStatement st = con.prepareStatement(sql);
            for (int l = 0; l < E.getEname().length; l++) 
            {
                st.setString(1, E.getEname());

            }
        }

    catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}


}

I believe the problem comes from the way you define Employee.ename a array of strings. Just use private String ename; instead

String[] ename is an array of strings, not a single string. You can save it in the database in 2 ways:

1) A separate table for enames

The correct way is to create a separate ename table with columns:

employeeId
ename

Create a compound primary key on (employeeId, ename).

Then save each ename as a separate row in the ename table. Then read Employee from the database, you will need to read all enames from the ename table by employeeId.

For example, let's say we have Employee with id=1 and ename=["name1","name2"]. We will have the following data in the ename table in the database:

employeeId | ename
------------------
          1| name1
          1| name2

2) Serialize String[] to String

You can serialize ename array to a single string (as a JSON, XML, comma-separated value) and store a single string value in the database.

When you read data from the database, you need to deserialize from String to String[].

For example, let's say we have Employee with id=1 and ename=["name1","name2"]. We will have the following data in the Employee table in the database if data was serialized as JSON:

    employeeId | ename
---------------------------------------
             1 | ["name1","name2"]  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM