how to insert variable into a table in MySQL

2019-08-10 02:57发布

问题:

I know how to add data into a table. Like

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

11.1 and 12.1 can be inserted into table. Now given a float variable

float fv = 11.1;

how to insert fv into the table?

回答1:

In JAVA, you can use prepared statements like this:

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:

I recommend you use a Prepared Statement, as follows:

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