【问题标题】:How to convert Arraylist varchar to int for an sql statement?如何将 Arraylist varchar 转换为 int 以用于 sql 语句?
【发布时间】:2021-06-15 07:03:59
【问题描述】:

我总是收到错误提示,sql 语句中的 arraylist 是 varchar 而不是 int。我试图在一个整数变量中解析数组列表,但它一直给我同样的错误。

代码:

try {
                String s = getIDUsuario().toString();
                String s1 = s.split(" ")[1];
                int id = Integer.parseInt(s1.charAt(2) + "");

                Statement st = dataBase.conexionBD().createStatement();

                ResultSet rs = st.executeQuery(" select *  from Serveis where id_servei = " + id + "");


                while (rs.next()) {

                    bytes = rs.getBytes("imatge_servei");
                    image = new BitmapDrawable(getResources(), BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
                    try {
                        listaObjeto.add(new InfoServicio(getNombre(), rs.getString("titol"), rs.getString("descripcio"), getImagenPerfil(), image));


                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            } catch (Exception e) {

            }
   

【问题讨论】:

  • 那是因为当你在查询中说它是一个字符串(varchar)时,当你用撇号'id'包围它时。删除它们并重试。但你真的应该使用带参数的prepared statement
  • 我做了,但还是一样
  • 你为什么要问ArrayList?您的代码中没有ArrayList,我没有得到相关性?
  • 即使您省略了单引号,您如何确定数据库将其检测为varchar?另外,您使用的是什么品牌的数据库引擎,数据库中id_servei 的数据类型是什么,查询是否返回所需的行或其他内容,如果是,那是什么?
  • 使用sql server,id_servei type int。

标签: java android mysql


【解决方案1】:

我不完全理解varchar '[3,4]' 的意思, 但如果你把它作为一个字符串,这就是你可能想要做的事情的要点。

  • 此字符串不完全类似于 int,因此您将无法对其进行解析。
String e = "varchar '[3,4]'";
String e2 = e.split(" ")[1]; // Split the string at SPACE and kept the last part.
// We can see that the numbers are at index 2 & 4 of the String e2.
// Therefore
int n1 = Integer.parseInt(e2.charAt(2) + ""); // Concatenated empty String with the char because the method takes a String.
int n2 = Integer.parseInt(e2.charAt(4) + ""); // Concatenated empty String with the char because the method takes a String.

【讨论】:

  • 您能否扩展您实际尝试解析的内容?是varchar ['3,4'] 还是[3,4]。是字符串还是别的什么?
  • 我想在语句 sql 中使用我的数组列表 getIDUsuario()
  • getIDUsuario() 返回整数数组列表
  • 是的,但是为什么要查询 db 的 arraylist 呢?你为什么不查询它的号码?如果要查询arraylist 中的每个数字,则必须对arraylist 中的每个元素使用循环和查询语句。你为什么不从你的arraylist中一一提取所有元素,然后查询它们?
  • 没有什么已经解决了,我只是把我的生活复杂化了
猜你喜欢
  • 2013-11-27
  • 2013-07-21
  • 1970-01-01
  • 2020-06-26
  • 2013-04-08
  • 1970-01-01
  • 1970-01-01
  • 2012-06-26
  • 2014-07-24
相关资源
最近更新 更多