0

I want to create a table and this table's name will be inserted from a textfield. However when I run the query it's giving me an error, any help on this one? I'll paste the code here:

public boolean CreateTable() {
  TableNumber = jTextField4.getText();

  try {            
    String password = null;
    String s = "CREATE TABLE '"+TableNumber+ "' (Item char(50),Price char(50))";

    ConnectionForOrders();
    stmt = conn.createStatement();
    stmt.executeUpdate(s);

    boolean f = false;
    ConnectionForOrdersclose();
7
  • 7
    What's the error? Commented Jun 9, 2010 at 21:30
  • 1
    Please fix your code formatting. Additionally, please provide more details on the error you are getting. Commented Jun 9, 2010 at 21:31
  • 5
    only YOU can prevent SQL injection! Be careful when you take a variable directly from a text field Commented Jun 9, 2010 at 21:34
  • Your tags can/do say both SQL and Java. The fact that you post means you have a question. Please think about your title a little more next time. Commented Jun 9, 2010 at 21:36
  • 1
    @colinmarc & OP - not only be careful, never ever do it this way. If you have to take parts of your SQL statement from user input then check the input (here:TableNumber) for malicous code/fragments Commented Jun 9, 2010 at 21:39

3 Answers 3

3

I'll start by assuming your '" gaff is a typo because it shouldn't even compile that way (I edited the question to fix it for those that come later).

That aside, you don't enclose tables names in single quotes. It's not:

CREATE TABLE 'tablename' ( ... )

You just write:

CREATE TABLE tablename ( ... )

But you shouldn't even do that much, because you're getting your tablename from a text field. What's to prevent someone from entering something like this in that text field:

a(b int);DROP TABLE users;--

(Assuming of course that you have a users table somewhere). It's important to remember that an attacker could enter any arbitrary sql after that first ;, and your database will blindly run it.

Sign up to request clarification or add additional context in comments.

Comments

1

Is TableNumber well...a number? If it is, it's probably causing a syntax error.

Comments

1

Looks like the apostrophe and quotation mark are inverted around TableNumber (the right side), which would produce a compiler error.

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.