2011-04-05 16 views
1

こんにちは、準備が整った文章にarraylistを渡そうとしていますが、次のエラーが表示されています。Arraylist/prepared statement

java.sql.PreparedStatementのsetString(int、java.lang.String)は、(int、java.lang.Object)に適用できません。 m_ps.setString(2、topics.get(1));ここで
^ は、トピックは、オブジェクトのリストであるので、あなたが)オブジェクトを文字列にキャストする必要があり、またはのtoStringを(呼びたいコード

public ArrayList<String> passTopics(String userName, ArrayList topics){ 
      m_ps = null; 
      String sql = null; 

     try{ 
      sql = "INSERT INTO adviceGiverTopics"+ "(userName,topics,dateAdded) VALUES(?, ?, ?)"; 
      m_ps = m_conn.prepareStatement(sql);  

      m_ps.setString(1,userName); 
      m_ps.setString(2, topics.get(1));   
      m_ps.setString(3, this.getDateTime()); 



      m_ps.execute(); 
      m_ps.close(); 
     } 
     catch(SQLException e){ 
      System.out.println(e.getMessage()); 
     } 

     return null; 
    } 
+0

私は(1)戻っている私は何topics.getに少しより多くの情報があればいいのに。 – Nican

+0

トピックのリストを返すと、助言者が議論できるように – Wanda

+0

待ち、ArrayListをsetStringに渡すことはできません。 StringはArrayListではありません。一致するデータを配置する必要があります。また、データベース構造と一致するデータを配置する必要があります。ブロブを入れたり、ある値を別の値にマッピングする新しいテーブルを作成したりすることができます。 – Nican

答えて

0

の一部です:

m_ps.setString(2, (String) topics.get(1));   

または m_ps.setString(2、topics.get(1).toString());

代わりに、ジェネリックスを使用し、トピックを "ArrayList <String>"と宣言しますが、それはあなたがまだ学んでいないことを推測しています。ここで

+0

それはうまくいきました。 – Wanda

1

は、私がそのコードを記述します。方法は次のとおりです。

package persistence; 

import java.sql.Connection; 
import java.sql.PreparedStatement; 
import java.sql.SQLException; 
import java.sql.Statement; 
import java.util.Date; 
import java.util.List; 

/** 
* B 
* @author Michael 
* @since 3/21/11 
*/ 
public class B 
{ 
    public static final String SQL = "INSERT INTO adviceGiverTopics" + "(userName,topics,dateAdded) VALUES(?, ?, ?)"; 

    private Connection connection; 

    public int saveTopics(String userName, List<String> topics, Date insertDate) 
    { 
     if ((userName == null) || "".equals(userName.trim())) 
      throw new IllegalArgumentException("user name cannot be null or blank"); 
     if ((topics == null) || (topics.size() < 2)) 
      throw new IllegalArgumentException("topics cannot be null and must have at least two elements"); 

     int numRowsAffected = 0; 

     PreparedStatement ps = null; 
     String sql = null; 

     try 
     { 
      ps = connection.prepareStatement(sql); 

      ps.setString(1, userName); 
      ps.setString(2, topics.get(1)); 
      ps.setDate(3, new java.sql.Date(insertDate.getTime())); 

      numRowsAffected = ps.executeUpdate(); 
     } 
     catch (SQLException e) 
     { 
      e.printStackTrace(); 
      throw new RuntimeException(e); 
     } 
     finally 
     { 
      close(ps); 
     } 

     return numRowsAffected; 
    } 

    private static void close(Statement st) 
    { 
     try 
     { 
      if (st != null) 
      { 
       st.close(); 
      } 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 
    } 

}