how to insert variable into a table in MySQL
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 va开发者_开发问答riable
float fv = 11.1;
how to insert fv into the table?
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();
}
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();
精彩评论