Arraylist / prepared statement



嗨,我试图传递一个数组列表到一个准备好的语句,但我得到以下错误。

setString(int,java.lang.String)在java.sql.PreparedStatement中不能应用于(int,java.lang.Object)m_ps。setString (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;
    }

我是这样写代码的:

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

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

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

或m_ps。setString (topics.get (1) .toString ());

另一种选择是使用泛型,并将主题声明为"ArrayList"——但我猜你还没学会。

相关内容

  • 没有找到相关文章

最新更新