Delete all tables of Database - java

I have a Database named KG. I want to delete all tables in this Database using java and then create them again (purpose is to truncate ALL data. Deleting tables as per advice of someone here at stackoverflow). What i need is a single command that can delete all tables. From this link i took this command
Drop Database KG
This command is not working with my case. Is there any other way to delete all Tables?
Editted
Code I am Using is
{
dbConnect();
try {
stmt = c.createStatement();
sql = "Drop Database KG";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
System.out.println("Database Deleted!");
} catch (SQLException e) {
System.err.println("Delete Database Query: " + sql);
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
and
public void dbConnect() {
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:KG.s3db");
c.setAutoCommit(false);
System.out.println("Connected");
} catch (ClassNotFoundException | SQLException e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
Error i am getting is
Delete Database: Drop Database KG
java.sql.SQLException: near "Database": syntax error
Note:
I have achieved it but by writing a large number of Lines of Code. Used command
Drop Table If Exists tablename
did this in loop.

You can not drop a sqlite database. Just delete the database file and open the database again.

Related

Inserting values to sqlite table results in error: [SQLITE_CONSTRAINT] Abort due to constraint violation (UNIQUE constraint failed: salesman.code)

I have created a fully-functional java app with mysql db. I have to change the mysql db to sqlite db to make the app more portable (no installation required). I'm in the process of converting all my mysql tables and values to sqlite.
I was to create the database and tables and now, I'm populating my salesman table from a .csv file selected by the user through FileChooser. After the user selects .csv file that would populate the salesman table, NetBeans would result to this error:
java.sql.SQLException: [SQLITE_CONSTRAINT] Abort due to constraint violation (UNIQUE constraint failed: salesman.code)
at org.sqlite.core.DB.newSQLException(DB.java:890)
at org.sqlite.core.DB.newSQLException(DB.java:901)
at org.sqlite.core.DB.execute(DB.java:810)
at org.sqlite.core.DB.executeUpdate(DB.java:847)
at org.sqlite.jdbc3.JDBC3PreparedStatement.executeUpdate(JDBC3PreparedStatement.java:86)
After researching for similar problems, it would mean that the values I'm putting in the salesman table are not aligned with the parameters / constraint set with the salesman table. But when I created the table, I did not put any UNIQUE constraint. I made the table using Browser for SQLite and this is the code for creating database and tables:
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:sandapp.db");
String createSalesmanQuery = "CREATE TABLE IF NOT EXISTS salesman (\n" +
" code INTEGER PRIMARY KEY\n" +
" NOT NULL,\n" +
" name TEXT NOT NULL\n" +
")\n" +
"WITHOUT ROWID;";
ps = conn.prepareStatement(createSalesmanQuery);
ps.executeUpdate();
String emptySalesmanQuery = "DELETE FROM salesman;"; //empties if there are contents
ps = conn.prepareStatement(emptySalesmanQuery);
ps.executeUpdate();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
The constraint WITHOUT ROWID is there because the attribute code are coming from another database, so there shouldn't be a table id that auto-increments. I already checked the .csv file where all the values for column codes are and there are no repeating values. This file was also used for mysql db and it uploaded successfully. Anyone have any ideas?
EDIT: Here is my method that gets the salesman details from a .csv file
public static String getSalesmanFromFile(String filePath){
ArrayList<Salesman> salesmanList= new ArrayList<Salesman>();
String status = null;
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line = null;
String[] strSalesman = null;
try {
Class.forName("org.sqlite.JDBC");
Connection connection = DBConnection.getConnection();
PreparedStatement ps = null;
while ((line=br.readLine()) != null){
strSalesman = line.split(",");
salesmanList.add(new Salesman(Integer.parseInt(strSalesman[0]), strSalesman[1]));
String insertSalesmanQuery = "INSERT INTO salesman VALUES(?, ?);";
ps = connection.prepareStatement(insertSalesmanQuery);
for(int i = 0; i<salesmanList.size(); i++){
ps.setInt(1, salesmanList.get(i).getCode());
ps.setString(2, salesmanList.get(i).getName());
ps.executeUpdate();
}
status = "Successfully uploaded";
}
ps.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
status = "Error"; //- Please review file selected. Make sure that format is followed.";
System.out.println(status);
}
return status;
Here are sample Salesman details from .csv file:
5099 JONATHAN REYES
5010 EDWIN DAVID
These two values return the error stated above in the Output log in NetBeans.

Create and connect to an SQL database using Java

I have a Java program that connects to an SQL database, and can write and read from it, however, in order to use the program, I first have to open Workbench, and run an SQL query in there.
Obviously, this isn't a great solution, so how can I create and connect to a database all within the Java code?
I've searched online, including the Oracle site, but can't see to get it.
Below is my code.
public Connection ConnectNow() //Connect to the database
{
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception ex)
{
System.out.println("Error 1");
ex.getMessage();
}
final String dbURL = "jdbc:mysql://localhost/game1"; //replace 'assignex' with database name
Connection conn = null;
try
{
conn = DriverManager.getConnection(dbURL, "root", "password");
System.out.println("\n== Connection Successful ==");
return conn;
}
catch (SQLException ex)
{
System.out.println("Error 2");
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
return null;
}
}
public void CreateDatabase()
{
try
{
Connection conn = ConnectNow();
Statement stmt = conn.createStatement();
String createDatabase = "CREATE DATABASE IF NOT EXISTS game1"; //creates database
stmt.executeUpdate(createDatabase);
conn.close();
stmt.close();
System.out.println("<< Database created successfully >>");
}
catch (Exception ex)
{
System.out.println("Error 7");
ex.getMessage();
ex.printStackTrace();
}
}
public void CreateTable() //creates a table within the database
{
try
{
Connection conn = ConnectNow();
Statement stmt = conn.createStatement();
String createTable = "CREATE TABLE IF NOT EXISTS user" +
"(firstname VARCHAR(255), " + //AUTO_INCREMENT to add numbers automatically
" surname VARCHAR(255), " +
" day INTEGER, " +
" month INTEGER, " +
" year INTEGER, " +
" username VARCHAR(255) NOT NULL, " +
" password VARCHAR(255), " +
" PRIMARY KEY (username))";
stmt.executeUpdate(createTable);
conn.close();
stmt.close();
System.out.println("<< Table created successfully >>");
}
catch (Exception ex)
{
System.out.println("Error 6");
ex.getMessage();
ex.printStackTrace();
}
}
Presumably, it's something to do with me attempting to connect before creating the database, but I can't find the solution to implement this correctly.
Help is much appreciated.
You already answered you own question. Your connection URL (jdbc:mysql://localhost/game1) specifies the database (game1) to connect to, but that database does not exist. If you look at your Exception output is is probably telling to exactly that. Your app should NOT be creating the database. It should just be connecting to it and modifying it. You can try to set the URL to not include the database name and then just use the MySQL USE command to specify a database but that is a lot of un-nessasary work. Just do not have the app create it's database.
maybe you could try declaring your port and host separately as strings like the following and create the database then you should be okay.
`import java.sql.*;
public class Test {
public static void main(String args[]) {
Connection con;
try {
**String server = "localhost";
String port = "50000";** //generic port for DB2 jdbc
String url = "jdbc:db2://"+server+":"+port+"/sample"; String userid = ”userid";
String password = ”password";`

JDBC update using prepared statement

I am trying to update a table using Java JDBC. The method I am using does not throw any errors but the table is not updating. The create table method is below:
public static void Table()
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS CUSTOMERS2 " +
"(PHONE TEXT PRIMARY KEY NOT NULL," +
" SURNAME TEXT NOT NULL, " +
" FIRSTNAME TEXT NOT NULL, " +
" HOME TEXT, " +
" ADDRESS TEXT, " +
" POSTCODE Text)";
stmt.executeUpdate(sql);
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Customers2 created successfully");
}
The update method is below:
public static void updateCustomers()
{
Connection c = null;
PreparedStatement pstmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
String query = "UPDATE CUSTOMERS2 set ADDRESS = ? where PHONE = ? ";
pstmt = c.prepareStatement(query); // create a statement
pstmt.setString(1, "1"); // set input parameter 1
pstmt.setString(2, "DOES THIS WORK"); // set input parameter 2
pstmt.executeUpdate(); // execute update statement
pstmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Update Completed successfully HELLO");
}
I have tried to find some clear instructions on this but cant find any. I do not really understand JDBC and prepared statement very well
When autoCommit is false (c.setAutoCommit(false);), you must manually commit the transaction...
Add...
c.commit()
After pstmt.executeUpdate();
You code also has a flaw, in that if some kind of error occurs during the preparation or execution of the statement, both the Connection and PreparedStatement could be left open, causing a resource leak
If you're using Java 7+ you can use the try-with-resources feature, for example...
try {
Class.forName("org.sqlite.JDBC");
try (Connection c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db")) {
c.setAutoCommit(false);
System.out.println("Opened database successfully");
String query = "UPDATE CUSTOMERS2 set ADDRESS = ? where PHONE = ? ";
try (PreparedStatement pstmt = c.prepareStatement(query)) {
pstmt.setString(1, "1"); // set input parameter 1
pstmt.setString(2, "DOES THIS WORK"); // set input parameter 2
pstmt.executeUpdate(); // execute update statement
c.commit();
}
} catch (SQLException exp) {
exp.printStackTrace();
}
} catch (ClassNotFoundException exp) {
exp.printStackTrace();
System.out.println("Failed to load driver");
}
This will ensure that regardless of how you leave the try block the resource will be closed.
You might also consider taking a look at the JDBC(TM) Database Access
Your update method will set ADDRESS to 1 if there is any row in table with PHONE = does this work.
Try to put Address in 1st Input parameter and Phone 2nd Input parameter
When a connection is created, it is in auto-commit mode.
We need to use [setAutoCommit] method only when we need to make Auto Commit false and make it manual commit after executing the query.
More details at Oracle site on JDBC Transaction.

SQLite - executeUpdate exception not caught when database does not exist? (Java)

So I was purposely trying to break my program, and I've succeeded.
I deleted the sqlite database the program uses, while the program was running, after I already created the connection. Then I attempted to update the database as seen below.
Statement stmt;
try
{
stmt = Foo.con.createStatement();
stmt.executeUpdate("INSERT INTO "+table+" VALUES (\'" + itemToAdd + "\')");
}
catch(SQLException e)
{
System.out.println("Error: " + e.toString());
}
The problem is, it didn't catch the exception, and continued to run as if the database was updated successfully. Meanwhile the database didn't even exist at that point since this was after I deleted it.
Doesn't it check if the database still exists when updating?
Do I have to check the database connection manually, every time I update to ensure that the database wasn't corrupted/deleted?
Is this the way it is normally done, or is there a simpler/more robust approach?
Thank you.
Interestingly, I found that if I delete my database when using it and then attempt to update it, it updates the database in its new location (in the trash!). You cannot permanently delete it while it is in the trash can and you are accessing it via your program.
It looks like this is not a SQLException that is thrown...
Try catching every Exception type and see if you get your error :
Statement stmt;
try
{
stmt = Foo.con.createStatement();
stmt.executeUpdate("INSERT INTO "+table+" VALUES (\'" + itemToAdd + "\')");
}
catch(Exception e)
{
System.out.println("Error: " + e.toString());
}
or
Statement stmt;
try
{
stmt = Foo.con.createStatement();
stmt.executeUpdate("INSERT INTO "+table+" VALUES (\'" + itemToAdd + "\')");
}
catch(Throwable e)
{
System.out.println("Error: " + e.toString());
}

Connecting to MySQL using Java on Debian

I am trying to connect to MySQL database with Java and I get the following error:
SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '????????????????' at line 1
I cannot understand the error and searched a lot on the web but did not found anything. This is the code I am using:
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception E)
{
System.err.println("Unable to load driver");
E.printStackTrace();
}
try
{
Connection C = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/DATABASE_NAME","USERNAME","PASSWORD");
Statement Stmt = C.createStatement();
ResultSet RS = Stmt.executeQuery("SELECT somefield FROM sometable");
while (RS.next())
{
System.out.print("\"" + RS.getString(1) + "\"");
System.out.print(" by " + RS.getString(2));
System.out.println(": " + RS.getString(3));
}
C.close();
RS.close();
Stmt.close();
}
catch (SQLException E)
{
System.out.println("SQLException: " + E.getMessage());
System.out.println("SQLState: " + E.getSQLState());
System.out.println("VendorError: " + E.getErrorCode());
}
The SQL query above is an example for the question. The one I am using works without any problem in MySQL console. In fact, even if I remove the query and the statement from the code above, I still get the same error.
Can someone help?
Thanks in advance
Most likely it's because you're using
select field from table- table is a SQL reserved word. If you want to do this query, you'll probably need to do
select field from `table`
with the word table in back ticks.

Categories

Resources