1

I am new to java programming and still learning. I am trying to make a table in my database (in xammp) using sql code in Java.

I found no any error but the code just failed to execute.. I've tried fixed it many times and still have no any progress..

Maybe somebody know how to fix my program, please tell me.. That would be great.

I use NetBeans btw..

This is my source code :

private void saveActionPerformed(java.awt.event.ActionEvent evt) {                                     
    String name=category_name_tf.getText();

        try  {
            Statement statement=(Statement) konek.GetConnection().createStatement();
            statement.execute("CREATE TABLE '"+name+"'('"+jakarta+"','"+bogor+ "','"
                +depok+ "','"+tangerang + "','"+bekasi+"');");//Is this codes right?
            statement.close();

            JOptionPane.showMessageDialog(null,"New Category Added");

            category_name_tf.setText("");
        }catch (Exception t){
            JOptionPane.showMessageDialog(null,"Add Category Failed");
            category_name_tf.requestFocus();
        }


}              
2
  • 2
    delete ALL ' and remove the ; at the end. also your input of the textfields need to contain the column name and the type in this format name type Commented Dec 8, 2016 at 11:44
  • Your execute statement should reflect this once complete Commented Dec 8, 2016 at 11:46

1 Answer 1

3

Refer this code and make changes


public class Test {
        public static void main(String[] args) throws ClassNotFoundException, SQLException {
            String tableName = "demo";
            String column1 = "Id";
            String column1Type = "int";
            String column2 = "name";
            String column2Type = "varchar(30)";
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/sample";
            Connection connection = DriverManager.getConnection(url, "username", "password");
            Statement stmt = connection.createStatement();
            String query = "create table " + tableName + " ( " + column1+" " + column1Type +  " , " +
                    column2 +" " + column2Type + " )";
            System.out.printf(query);
            stmt.executeUpdate(query);
            stmt.close();
        }
    }

Don't forget to close your connection and Statement Objects

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

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.