如何将变量插入MySQL中的表中

时间:2011-07-03 22:51:06

标签: java jdbc insert prepared-statement

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

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 个答案:

答案 0 :(得分:6)

在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();
}

答案 1 :(得分:1)

我建议您使用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();