【问题标题】:Trying to create user defined database [duplicate]尝试创建用户定义的数据库[重复]
【发布时间】:2017-02-23 19:35:28
【问题描述】:
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");
    }

}

【问题讨论】:

  • 您是否收到任何错误,您的表格是否已创建,您的问题究竟是什么?
  • 您不能参数化对象标识符,如表名

标签: java sql oracle swing jdbc


【解决方案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(),所以你可以在开头和结尾更改''"",因为"在 oracle 中允许create a table with a name which contain spaces。

【讨论】:

    猜你喜欢
    • 2017-11-02
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多