gpt4 book ai didi

java - 使用java将arraylist值插入到sql server数据库中

转载 作者:行者123 更新时间:2023-11-30 08:43:56 26 4
gpt4 key购买 nike

我是 android 编程的新手,我遇到了一个小问题。我有一个数组列表,其中包含从多选 ListView 中选择的人名,问题是每当我将这些数组列表值插入数据库时​​,它都会将其作为一个字符串插入: Database row .我如何遍历数组列表并同时将其值插入数据库?

这是我的代码:

try {
Connection con = connectionClass.CONN();
if (con == null) {
Toast.makeText(getApplicationContext(), "CONNECTION FAIL", Toast.LENGTH_LONG).show();
} else {

String samp = "";
String names = "";
samp = myArrayAdapter.getCheckedItems().toString();
ArrayList<String> data1 = new ArrayList<String>();
data1.add(samp);

for(int x=0; x<data1.size(); x++)
{
names += String.valueOf(data1.get(x));
String query = "INSERT INTO AUTOINC(PersonName)"+"VALUES('"+names+"')";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();

}
Toast.makeText(getApplicationContext(), "INSERT SUCCESS", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "INSERT FAILED", Toast.LENGTH_LONG).show();
Log.e("MYAPP", "exception", ex);
}

感谢您以后的任何回复。

最佳答案

你能试试吗?

List<String> data1 = new ArrayList<String>(Arrays.asList(samp.replace("[","").replace("]","").split(",")));

for (String name : data1) {
names += name; // This lines concatenate the name.
//If you want to insert single name the you can directly insert the name value into databas.
String query = "INSERT INTO AUTOINC(PersonName)"+"VALUES('"+name+"')";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
}

关于java - 使用java将arraylist值插入到sql server数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33995178/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com