如何使用java在Mysql数据库中插入数组值

问题描述 投票:0回答:1

我想要将这些值插入 mysql 数据库的一个字段中:

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");
java mysql jdbc
1个回答
0
投票

我使用这种方式使用 MySQL Connector 8.0.23.jar 将数据从 Java 插入到我的 SQL 中

首先是数组:

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"},
    };

第二个我向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();
    }
}

我希望它可以帮助您使用第二种方法,我使用双精度作为 id,第二个 f 用于每列插入数据

declaracion.setString(c+2, datosEnviar[nId-1][c]);

© www.soinside.com 2019 - 2024. All rights reserved.