how to insert variable into a table in MySQL

放肆的年华 提交于 2019-12-24 09:48:17

问题


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


来源:https://stackoverflow.com/questions/6566031/how-to-insert-variable-into-a-table-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!