Reputation: 77
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();
}
}
Upvotes: 1
Views: 9097
Reputation: 3216
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
Upvotes: 3