有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在MySQL中向表中插入变量

我知道如何将数据添加到表中。就像

String insertQuery = "INSERT INTO tablename (x_coord, y_coord)"
                            +"VALUES"
                            +"(11.1,12.1)";
s.execute(insertQuery);

11.1和12.1可以插入表中。现在给出一个浮点变量

float fv = 11.1;

如何将fv插入表中


共 (2) 个答案

  1. # 1 楼答案

    在JAVA中,您可以使用如下准备好的语句:

    Connection conn = null;
    PreparedStatement pstmt = null;
    
    float floatValue1 = 11.1;
    float floatValue2 = 12.1;
    
    try {
        conn = getConnection();
        String insertQuery = "INSERT INTO tablename (x_coord, y_coord)"
                            +"VALUES"
                            +"(?, ?)";
        pstmt = conn.prepareStatement(insertQuery);
        pstmt.setFloat(1, floatValue1);
        pstmt.setFloat(2, floatValue2);
        int rowCount = pstmt.executeUpdate();
        System.out.println("rowCount=" + rowCount);
    } finally {
        pstmt.close();
        conn.close();
    }
    
  2. # 2 楼答案

    我建议您使用Prepared Statement,如下所示:

    final PreparedStatement stmt = conn.prepareStatement(
            "INSERT INTO tablename (x_coord, y_coord) VALUES (?,?)");
    stmt.setFloat(1, 11.1f);
    stmt.setFloat(2, 12.1f);
    stmt.execute();