尝试创建用户定义的数据库

时间:2017-02-23 19:35:29

标签: java sql oracle swing jdbc

public void create(String name) {
    create_name = name;
    try {
        getConnection();
        q = "create table ? (emp_id number (10), emp_name varchar (15))";
        pst = con.prepareStatement(q);

        pst.setString(1, create_name);
        int j = pst.executeUpdate();

        JOptionPane.showMessageDialog(new JDialog(), "Table is Created");

    } catch (Exception e) {
        JOptionPane.showMessageDialog(new JDialog(), "Table is not Created");
    }

}

1 个答案:

答案 0 :(得分:1)

要创建一个包含PrepapredStatement的表,这是不可能的,因为当您创建

q= "create table ? (emp_id number (10), emp_name varchar (15))";

所以实际上它会在这里执行这个查询:

create table 'table_name' (emp_id number (10), emp_name varchar (15))

并且在您创建表格时禁止'table_name',所以我建议您使用PrepapredStatement这样的内容:

try {
    Class.forName(driver);
    Connection connection = DriverManager.getConnection(DB_URL, DB_username, DB_password);
    PreparedStatement preparedStatement = connection.prepareStatement("create table ? (emp_id number (10), emp_name varchar (15))");
    preparedStatement.setString(1, "table_name");

    System.out.println(preparedStatement.toString());
    Statement st = connection.createStatement();
    int i = st.executeUpdate(preparedStatement.toString().replaceAll("\"", "\""));

    JOptionPane.showMessageDialog(new JDialog(), "Table is Created");        

} catch (ClassNotFoundException | SQLException e) {
    JOptionPane.showMessageDialog(new JDialog(), "Table is not Created");
}

当您准备语句时,这个想法很简单,您将获得上一个查询,您可以像preparedStatement.toString()一样获取它,这样您就可以在{{1}开头和最后更改''因为create a table with a name which contain spaces在oracle中允许""