Inzimam Tariq IT Inzimam Tariq IT - 1 year ago 105
Java Question

No database selected Error While Creating Table in MySQL with Java

I have Created a database with this code Some days ago

sql = "Create Database if not exists My_Test_Project";

And Created Some tables at that time. Now I'm creating two new tables in it one with this query

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))";

And when I Executed my program it throw Exception

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

But at the same time this query executed successfully

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))";

Note: Sales_Invoice table is first in sequence and in code too.
I do not know why its throwing exception. Can you please guide me.

Answer Source

I would believe in this line you will need to add the Database name:

REFERENCES Sales_Invoice (sale_inv_id)

So it should now be:

 REFERENCES My_Test_Project.Sales_Invoice (sale_inv_id)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download