我有一个包含多行的ListView
。当我将 ListView 中的条目插入 SQL 数据库时,所有条目都会插入到一行中。
我使用字符串生成器从 View 中获取所有条目。
如何解决这个问题?
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
StringBuilder sb3 = new StringBuilder();
//get data form text view
for(int i=0; i<simpleAdapter.getCount(); i++) {
String a = ((TextView) findViewById(R.id.al)).getText().toString();
String b = ((TextView) findViewById(R.id.sh)).getText().toString();
String c = ((TextView) findViewById(R.id.acc)).getText().toString();
simpleAdapter.getItem(i).toString();
sb.append(a);
sb.append("\n");
sb2.append(b);
sb2.append("\n");
sb3.append(c);
sb3.append("\n");
}
String text = sb.toString();
String text2 = sb2.toString();
String text3 = sb3.toString();
//my sql connection insert query
try {
Connection con = connectionClass.CONN();
if (con == null) {
Toast.makeText(getApplicationContext(), "Error in connection with SQL server", Toast.LENGTH_LONG).show();
} else {
String query = "INSERT INTO suigen.TransAlmiraShelf (Almira, Shelf, AccessionNo) VALUES('" + String.valueOf(text) + "','" + String.valueOf(text2) + "','" + String.valueOf(text3) + "')";
Statement stmt = con.createStatement();
stmt.execute(query);
Toast.makeText(Main13Activity.this, "Your Data Successfully Saved", Toast.LENGTH_LONG).show();
}
}
catch (Exception ex) {
Toast.makeText(getApplicationContext(), "Exceptions", Toast.LENGTH_LONG).show();
}
最佳答案
使用 JDBC 从表中获取值列表
Connection connection = DriverManager.getConnection("URL", "USERNAME",
"PASSWORD");
PreparedStatement statement = connection.prepareStatement("select * from
table");
ResultSet resultSet = statement.executeQuery();
if (resultSet != null) {
while (resultSet.next()) {
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
int type = resultSetMetaData.getColumnType(i);
if (type == Types.VARCHAR || type == Types.CHAR) {
System.out.println(resultSet.getString(i));
} else {
System.out.println(resultSet.getLong(i));
}
}
System.out.println("-----------");
}
}
关于java - 所有 ListView 数据仅插入一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45529953/