'How to insert array values in Mysql database using java
What i want insert these values in one field of mysql database :
String[] content = {"a1", "a2", "a3", "a4"};
aArray
...?//how can i write the code here..help me
String query = "insert into CHAR_ARRAY_TABLE(id, cont) values(?,?)";
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, row_id_name);
preparedStatement.setArray(2, aArray);
int count = preparedStatement.executeUpdate();
System.out.println(count + " inserted");
Solution 1:[1]
Iam using this way to insert data into my SQL from Java using MySQL Connector 8.0.23.jar
First the array:
Connection conexion = null;
Statement instr = null;
ResultSet contenido = null;
public static String datosEnviar [][] =
{ {"Tierra", "Rocoso", "6371"},
{"Jupiter", "Gaseoso", "71492"},
{"Urano", "Helado", "28709"},
{"Mercurio", "Rocoso", "2440"},
};
Second the way i insert data into MySQL.
public void Insertar()
{ String comando = "insert into tablaPiramides (id, planeta, tipo, radio)"
+" values (?,?,?,?)";
ResultSetMetaData datos;
@SuppressWarnings("unused")
int nc=0;
try {
datos = contenido.getMetaData();
nc = datos.getColumnCount();
} catch (SQLException e1) {
e1.printStackTrace();
}
PreparedStatement declaracion;
try {
declaracion = conexion.prepareStatement(comando);
for (int nId=1; nId<=4; nId++) {
declaracion.setInt(1, nId);
for (int c=0; c<3; c++) {
declaracion.setString(c+2, datosEnviar[nId-1][c]);
} declaracion.executeUpdate();
}
//declaracion.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
I hope it can help you in the second method, iam using a double for one for ids, and a second f for insert data each column declaracion.setString(c+2, datosEnviar[nId-1][c]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
