简体   繁体   中英

Create Table Database Using SQL in Java

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


}              

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM