1

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?

3
  • 5
    What programming language are you using? Commented Jul 3, 2011 at 22:53
  • @eyazici I am using java Commented Jul 3, 2011 at 22:54
  • @wzb5210 Use prepared statements, see my answer. Commented Jul 3, 2011 at 23:00

2 Answers 2

6

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();
}
Sign up to request clarification or add additional context in comments.

4 Comments

@Emre Yazıcı By the way, I have a new question. How to insert an array as a string into the database. Like "11.1,12.1" is a string, but how to let "floatValue1,floatValue2" works?
@wzb5210 Why do you asking me? I am not the owner of the most suitable answer.
@Emre Yazıcı Oh, I am sorry, I just found the problem. I thought i could accept all correct answers. So I clicked your answer and then clicked another. I just realized that I could only accept one answer. Sorry for that.
@wzb5210 It does not matter. As for your question, please open a new question or update your question. Don't forget to give code example.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.