尝试转换 Arraylist<LatLng>在插入到数据库之前到字符串 [英] Try to convert Arraylist&lt;LatLng&gt; to string before insert to database

查看:23
本文介绍了尝试转换 Arraylist<LatLng>在插入到数据库之前到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试插入我的 ArrayListlist1 有很多这样的值:(99.9999999,99.9999999) 到 MySQL 数据库中的表,精确到 1 列,如下所示:

I try to insert my ArrayList<LatLng> list1 with a lot of values like this: (99.9999999,99.9999999) to table in database MySQL, exacly to 1 column, something like this:

row 1 (99.9999999,99.9999999)  
row 2 (99.9999999,99.9999999)  
row 3 (99.9999999,99.9999999)

...全部为 1 列.

... all to 1 column.

在我看来,目前我有一个很好的方法:

In my opinion, currently i have a good method for this:

String sql = "INSERT INTO table1 VALUES(";
for(String s : list1) {
    sql = sql+"'"+s+"'"; 
}    
sql = sql+")";
stmt.executeUpdate(sql);

但 Android Studio 在 String s 下划线并说:

but Android Studio underlines String s and says:

Incompatible types
Required: com.google.android.gms.maps.model.LatLng
Found: java.lang.String

在我看来,Android Studio 试图告诉我:您需要转换 ArrayList 中的所有值.list1String !
是否可以用一种方法转换我的 ArrayList 中的所有值?

In my opinion, Android Studio trying to say me: you need to convert all values from ArrayList<LatLng> list1 to String !
Is it possible to convert all values from my ArrayList in one method ?

推荐答案

糟糕的做法:

您可以通过以下方式将数据转换为字符串:

You can convert your data to string the following way:

for(LatLng s : list1)
{
    String sql = "INSERT INTO table1 VALUES('"+s+"');
    stmt.executeUpdate(sql);
}

也就是说,您无需执行任何特定操作即可对其进行转换.我假设您在 LatLng 类中实现了 toString() 方法,以便为 LatLng 类型的对象提供有意义的字符串表示.

That is, you don't have to do anything specific to convert it. I'm assuming you have the method toString() implemented in your LatLng class to give objects of LatLng type a meaningful string representation.

这样做的好方法:

String sql = "INSERT INTO table1 VALUES(?)";
PreparedStatement stmt = dbConnection.prepareStatement(sql);
for(LatLng s : list1){
    stmt.setString(1, s); // insert 's' in place of the 1st '?'
    stmt.addBatch();
}
stmt.executeBatch();

在最后一种情况下,您正在准备一批命令以立即发送到您的数据库.这比发送许多 sql 语句要好得多,因为您最终的开销要少得多.此外,您不是自己连接 sql 语句.你给初始的 sql 语句一个 '?'占位符,然后使用setString()"或setInt()"或您想要插入的任何类型插入值.

In this last case you are preparing a batch of commands to send at once to your database. This is much better than sending many sql statements because you end up having a lot less overhead. Also, you're not concatenating the sql statement by yourself. You give the initial sql statement with a '?' placeholder and then you insert the values with 'setString()' or 'setInt()' or whatever the type is of what you want to insert.

这篇关于尝试转换 Arraylist<LatLng>在插入到数据库之前到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆