Arraylist /准备好的声明

时间:2011-04-05 01:58:17

标签: arraylist prepared-statement

嗨我试图将一个arraylist传递给准备好的声明但是我得到了以下错误。

java.sql.PreparedStatement中的

setString(int,java.lang.String)不能应用于(int,java.lang.Object)             m_ps.setString(2,topics.get(1));
                ^ 这是代码的一部分

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;
    }

2 个答案:

答案 0 :(得分: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();
        }
    }

}

答案 1 :(得分:0)

由于主题是Object的列表,您必须将Object强制转换为String,或者调用toString():

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

或     m_ps.setString(2,topics.get(1).toString());

另一种方法是使用泛型,并将主题声明为“ArrayList&lt; String&gt;” - 但我猜这不是你已经学到的东西。