没有选择数据库使用Java在MySQL中创建表时出错

时间:2016-08-29 19:18:37

标签: java mysql exception database-connection

我几天前用这段代码创建了一个数据库

sql = "Create Database if not exists My_Test_Project";
            stmnt.executeUpdate(sql);

当时创建了一些表格。现在我在其中使用此查询创建两个新表

sql = "CREATE TABLE if not exists My_Test_Project.Sales_Invoice_Help "
                    + "(inv_help_id INTEGER,"                    
                    + "item VARCHAR(255),"
                    + "qty INTEGER,"
                    + "rate DECIMAL (7, 2),"
                    + "total DECIMAL (7, 2),"
                    + "sale_inv_id INTEGER,"
                    + " PRIMARY KEY (inv_help_id),FOREIGN KEY (sale_inv_id) REFERENCES Sales_Invoice (sale_inv_id))";
            stmnt.executeUpdate(sql);

当我执行我的程序时,它会抛出异常

SEVERE: null
java.sql.SQLException: No database selected

但同时此查询已成功执行

sql = "CREATE TABLE if not exists My_Test_Project.Sales_Invoice "
                    + "(sale_inv_id INTEGER not NULL, "
                    + "date VARCHAR(255), "
                    + "acc_name VARCHAR(255),"
                    + "due_date VARCHAR(255),"
                    + "customer_name VARCHAR(255),"
                    + "receipt_no VARCHAR(255),"
                    + "freight_charges INTEGER,"
                    + "deliver_to VARCHAR(255),"
                    + "deliver_date VARCHAR(255),"
                    + "total INTEGER,"
                    + "discount INTEGER,"
                    + "g_total INTEGER ,"
                    + " PRIMARY KEY (sale_inv_id))";
            stmnt.executeUpdate(sql);

注意: Sales_Invoice表是第一个顺序和代码。 我不知道为什么它抛出异常。你能指导我吗?

1 个答案:

答案 0 :(得分:0)

我相信这一行你需要添加数据库名称:

REFERENCES Sales_Invoice (sale_inv_id)

现在应该是:

 REFERENCES My_Test_Project.Sales_Invoice (sale_inv_id)