如何使用java在mySql的表列中存储数组值

时间:2013-04-22 09:56:12

标签: java mysql jsp liferay

你好我试图在两个结果集中检索数据。然后我将结果集存储到String Array中,在这个过程之后我必须将我的String数组存储到另一个表中,如何这样告诉我..

try {
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = (Connection) DriverManager.
         getConnection("jdbc:mysql://localhost:3306/lportal", "root", "ubuntu123");
    PreparedStatement stmt = (PreparedStatement) con.
         prepareStatement("SELECT * FROM  Testi_Testimonial where subject = ?");
    stmt.setString(1, search);
    stmt.execute();
    rs = (ResultSet) stmt.getResultSet();
    while (rs.next()) {
      anArray[i] = rs.getString("subject");
      System.out.println(anArray[i]);
      i++;
      count++;
    }
    PreparedStatement stmt1 = (PreparedStatement) con.
         prepareStatement("SELECT * FROM Testi_Testimonial where subject != ?");
    stmt1.setString(1, search);
    stmt1.execute();
    rs1 = (ResultSet) stmt1.getResultSet();
    while (rs1.next()) {
      anArray[i] = rs1.getString("subject");
      System.out.println(anArray[i]);
      i++;
      count++;
    }
} catch (Exception e) {
  e.printStackTrace();
  System.out.println("problem in connection");
}

请告诉我应该如何将我的数组存储到Temp表?我的“临时”表格列subject我要将myArray存储到subject列...请告诉我该怎么做。

3 个答案:

答案 0 :(得分:3)

在rs:

中获取结果集后尝试此操作
   PreparedStatement st = (PreparedStatement) con.prepareStatement("insert into temp values(?)");
    i=0;
   while(rs.next())
    {
      st.setString(1,anArray[i]);
      st.executeUpdate();
      i++;
    }

答案 1 :(得分:1)

您只需迭代arrayList。你将主题列表分别作为。

public class TestArrayList {
    public static void main(String[] args) {

        /*create two arrayList*/
        List<String> tempOneList = new ArrayList<String>();
        try {

            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vijay", "root", "root");
            Statement st = con.createStatement();

            ResultSet res = st.executeQuery("SELECT * FROM  subjecttable");

            while (res.next()) {
                tempOneList.add(res.getString("subject"));
            }

            ResultSet resOne = st.executeQuery("SELECT * FROM  subjecttabletwo");
            while (resOne.next()) {
                tempOneList.add(resOne.getString("subject"));
            }
            System.out.println("temp/List>>--" + tempOneList.size());
            for(int i=0;i<tempOneList.size();i++){
                System.out.println(tempOneList.get(i));
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("problem in connection");
        }
    }
}

答案 2 :(得分:0)

PreparedStatement ps = 
    (PreparedStatement) con.prepareStatement("insert into temp values(?)");

j=0;
while(rs.next())
{
    ps.setString(1,anArray[j]);
    ps.executeUpdate();
    j++;
}