【问题标题】:How to insert array values in Mysql database using java如何使用java在Mysql数据库中插入数组值
【发布时间】:2017-06-20 11:55:47
【问题描述】:

我想在 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");

【问题讨论】:

  • 您想在con列中将数组元素的值作为单个字符串插入吗?

标签: java mysql jdbc


【解决方案1】:

我正在使用这种方式使用 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();
    }
}

我希望它可以在第二种方法中对您有所帮助,我使用一个 double 作为 id,第二个 f 用于每列插入数据declaracion.setString(c+2, datosEnviar[nId-1][c]);

【讨论】:

    猜你喜欢
    • 2015-06-18
    • 2015-08-02
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 2020-08-11
    相关资源
    最近更新 更多