In Java, How to Drop Sqlite Table - java

hi i have tried this command on my sqlite database but it wont drop/delete my database table,
here my reference
Statement stmt = conn.createStatement();
String sqlCommand = "DROP TABLE 'myTable' ";
System.out.println("output : " + stmt.executeUpdate(sqlCommand));
//Output
output : 0
there are no return error so i still cant figure by myself what is making the code not working.
Code to Drop Table
Connection c = null;
Statement stmt = null;
String sql;
c = openSqlite(c); //method i create to setup sqlite database connection
stmt = c.createStatement();
try{
System.out.println("Deleting table in given database...");
String sqlCommand = "DROP TABLE 'myTable' ";
stmt.executeUpdate(sqlCommand);
System.out.println("Table deleted in given database...");
stmt.close();
c.commit();
c.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}

Thanks to MadProgrammer and other, Actually i miss to put commit statement on my code..
Statement stmt = conn.createStatement();
String sqlCommand = "DROP TABLE IF EXISTS 'myDatabase.myTable' ";
System.out.println("output : " + stmt.executeUpdate(sqlCommand));
stmt.close();
conn.commit(); // commit after execute sql command
//COMMIT TRANSACTION makes all data modifications performed since
//the start of the transaction a permanent part of the database,
conn.close();

Related

Using savepoints with the JDBC-ODBC Bridge: UnsupportedOperationException

I have connected NetBeans IDE with MS Access and while doing a transaction I got this error.
It seems that savepoints are not supported...Please guide me..
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:cse");
Statement stmt1, stmt2, stmt3;
System.out.println("Statements created");
conn.setAutoCommit(false);
String query1 = " update registration set id='105' " +
"where first = 'Sumit' ";
String query2 = " update registration set id='106' " +
"where first = 'Zayed' ";
System.out.println(" Queries created");
stmt1 = conn.createStatement();
System.out.println(" Connection created");
Savepoint s1 = conn.setSavepoint("sp1");
System.out.println(" Savept created");
stmt2 = conn.createStatement();
stmt1.executeUpdate(query1);
stmt2.executeUpdate(query2);
conn.commit();
stmt3 = conn.createStatement();
stmt1.close();
stmt2.close();
conn.releaseSavepoint(s1);
conn.close();
The error is
Statements created
Queries created
Connection created
Error: java.lang.UnsupportedOperationException
The JDBC-ODBC Bridge apparently does not support Savepoints at all. However, the UCanAccess JDBC driver does support unnamed Savepoints:
String connStr = "jdbc:ucanaccess://C:/__tmp/test.mdb";
try (Connection conn = DriverManager.getConnection(connStr)) {
conn.setAutoCommit(false);
try (Statement s = conn.createStatement()) {
s.executeUpdate("UPDATE ucaTest SET Field2='NEWVALUE1' WHERE ID=1");
}
java.sql.Savepoint sp1 = conn.setSavepoint();
try (Statement s = conn.createStatement()) {
s.executeUpdate("UPDATE ucaTest SET Field2='NEWVALUE2' WHERE ID=2");
}
conn.rollback(sp1);
conn.commit();
} catch (Exception e) {
e.printStackTrace(System.out);
}
For more information on using UCanAccess see
Manipulating an Access database from Java without ODBC

Execute multiple SQL statements in java

I want to execute a query in Java.
I create a connection. Then I want to execute an INSERT statement, when done, the connection is closed but I want to execute some insert statement by a connection and when the loop is finished then closing connection.
What can I do ?
My sample code is :
public NewClass() throws SQLException {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
return;
}
System.out.println("Oracle JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:orcl1", "test",
"oracle");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
return;
}
if (connection != null) {
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * from test.special_columns");
while (rs.next()) {
this.ColName = rs.getNString("column_name");
this.script = "insert into test.alldata (colname) ( select " + ColName + " from test.alldata2 ) " ;
stmt.executeUpdate("" + script);
}
}
else {
System.out.println("Failed to make connection!");
}
}
When the select statement ("SELECT * from test.special_columns") is executed, the loop must be twice, but when (stmt.executeUpdate("" + script)) is executed and done, then closing the connection and return from the class.
Following example uses addBatch & executeBatch commands to execute multiple SQL commands simultaneously.
import java.sql.*;
public class jdbcConn {
public static void main(String[] args) throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","name","pass");
Statement stmt = con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String insertEmp1 = "insert into emp values
(10,'jay','trainee')";
String insertEmp2 = "insert into emp values
(11,'jayes','trainee')";
String insertEmp3 = "insert into emp values
(12,'shail','trainee')";
con.setAutoCommit(false);
stmt.addBatch(insertEmp1);
stmt.addBatch(insertEmp2);
stmt.addBatch(insertEmp3);
ResultSet rs = stmt.executeQuery("select * from emp");
rs.last();
System.out.println("rows before batch execution= "
+ rs.getRow());
stmt.executeBatch();
con.commit();
System.out.println("Batch executed");
rs = stmt.executeQuery("select * from emp");
rs.last();
System.out.println("rows after batch execution= "
+ rs.getRow());
}
}
Result:
The above code sample will produce the following result.The result may vary.
rows before batch execution= 6
Batch executed
rows after batch execution= = 9
Source: Execute multiple SQL statements
In the abscence of the schema or the data contained in each table I'm going to make the following assumptions:
The table special_columns could look like this:
column_name
-----------
column_1
column_2
column_3
The table alldata2 could look like this:
column_1 | column_2 | column_3
---------------------------------
value_1_1 | value_2_1 | value_3_1
value_1_2 | value_2_2 | value_3_2
The table alldata should, after inserts have, happened look like this:
colname
---------
value_1_1
value_1_2
value_2_1
value_2_2
value_3_1
value_3_2
Given these assumptions you can copy the data like this:
try (
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl1", "test", "oracle")
)
{
StringBuilder columnNames = new StringBuilder();
try (
Statement select = connection.createStatement();
ResultSet specialColumns = select.executeQuery("SELECT column_name FROM special_columns");
Statement insert = connection.createStatement()
)
{
while (specialColumns.next())
{
int batchSize = 0;
insert.addBatch("INSERT INTO alldata(colname) SELECT " + specialColumns.getString(1) + " FROM alldata2");
if (batchSize >= MAX_BATCH_SIZE)
{
insert.executeBatch();
batchSize = 0;
}
}
insert.executeBatch();
}
A couple of things to note:
MAX_BATCH_SIZE should be set to a value based on your database configuration and the data being inserted.
this code is using the Java 7 try-with-resources feature to ensure the database resources are released when they're finished with.
you haven't needed to do a Class.forName since the service provider mechanism was introduced as detailed in the JavaDoc for DriverManager.
There are two problems in your code. First you use the same Statement object (stmt) to execute the select query, and the insert. In JDBC, executing a statement will close the ResultSet of the previous execute on the same object.
In your code, you loop over the ResultSet and execute an insert for each row. However executing that statement will close the ResultSet and therefor on the next iteration the call to next() will throw an SQLException as the ResultSet is closed.
The solution is to use two Statement objects: one for the select and one for the insert. This will however not always work by default, as you are working in autoCommit (this is the default), and with auto commit, the execution of any statement will commit any previous transactions (which usually also closes the ResultSet, although this may differ between databases and JDBC drivers). You either need to disable auto commit, or create the result set as holdable over commit (unless that already is the default of your JDBC driver).

how to insert value in ms access using java

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con1=DriverManager.getConnection("jdbc:odbc:MyDatabase");
st1=con1.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
System.out.println("Connect database in BallMoves1.java .......");
/*the below line giving error*/
rs1 = st1.executeQuery("insert into highscore" + " (score) " + "values('"+score+"')");
System.out.println("Score is inserted..");
System.out.println("Score......."+score);
}catch(Exception e){ e.printStackTrace();}
/*highscore is table and attributes of table are (sid,score).
the resulting error is:
Connect database in BallMoves1.java .......
java.sql.SQLException: No ResultSet was produced
at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(JdbcOdbcStatement.java:258)
at BallMoves1.move(BallMoves1.java:378)
at BallMoves1.run(BallMoves1.java:223)
at java.lang.Thread.run(Thread.java:744)*/
You're calling executeQuery on something that isn't a query. But instead of calling execute with the same SQL, you should use a PreparedStatement:
String sql = "insert into highscore (score) values (?)";
try (Connection conn = DriverManager.getConnection("jdbc:odbc:MyDatabase");
PreparedStatement statement = conn.prepareStatement(sql)) {
statement.setInt(1, score);
statement.executeUpdate();
conn.commit();
}
Always use parameterized SQL, instead of plugging the values directly into the SQL - that protects you from SQL injection attacks, conversion errors, and hard-to-read code.
Use a try-with-resources statement (as I have) to automatically close the statement and connection at the end of the block.

Dynamic Delete query

Im trying to make a dynamic Delete Query.
What im basically trying to do is first grab the name of the first column in any table (the primary key). Then i use that in Another Query to delete from that table though i get a nullpointerexception?
Ohh and the primary key is not an INT like 1,2,3,4,5 etc.. it's formed up as S1,S2,S3,S4,S5 etc and has the type TEXT.
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(true);
System.out.println("Opened database successfully");
ResultSet rs = stmt.executeQuery("SELECT * FROM "+tablename);
ResultSetMetaData rsmd = rs.getMetaData();
FirstColumn = rsmd.getColumnName(1);
String query = "DELETE FROM "+tablename+" WHERE " +FirstColumn+ " = " +row;
stmt = c.createStatement();
stmt.executeUpdate(query);
stmt.close();
c.close();
I am going to assume that all the variables you are using have been initialized.
I added single quotes around the FirstColumn name.
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(true);
System.out.println("Opened database successfully");
ResultSet rs = stmt.executeQuery("SELECT * FROM "+tablename);
ResultSetMetaData rsmd = rs.getMetaData();
FirstColumn = rsmd.getColumnName(1);
String query = "DELETE FROM "+ tablename +" WHERE " + FirstColumn + " = '" + row + "'";
stmt = c.createStatement();
stmt.executeUpdate(query);
stmt.close();
c.close();
If you are still getting an error you should try printing out your row name and see what it prints out.
Edit: Since you are new stylistically it's preferable to add a single space when using operators to improve code readability. For example 1+3+x+34 is a lot harder to read than 1 + 3 + x + 34. Granted there is no "wrong" code style but improving code readability is always a plus.
Initialize your stmt object...
stmt = c.createStatement();
before executing the query.

getting out parameter from mysql stored procedure in java

I am having problem retrieving OUT parameter from mysql stored procedure in java.
CALL proc_after_topic_add('newtest',#result);
SELECT #result;
this query gives me desired out parameter but how would i retrieve it in java.I tried using CallableStatement but i get
java.sql.SQLException: Callable statments not supported.
error.Please guys help me.
I have tried following
String sql = "CALL proc_after_topic_add(?,?);";
CallableStatement cstmt = conn.prepareCall(sql);
cstmt.setString(1, topicname);
cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
ResultSet rs = cstmt.executeQuery();
if (rs.next()) {
if (rs.getInt(1) == 1) {
res = 0;
} else {
res = -1;
}
}
I havent posted stored procedure code because there is nothing wrong with it.
PS:I a using mysql 5.5.21 and yes i should probably mention i am using mysql connector 3.0.15
Okay this is solved.For anyone who encounters the same problem,just download latest version of mysql connector.
Error in this line
cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
change like this
String sql = "CALL proc_after_topic_add(?,?);";
cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
Create a schema test and create a table employee in schema with 2 columns.
id and employeename and insert some data.
Use this Stored Procedure.
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`get_count_name1` $$
CREATE PROCEDURE `test`.`get_count_name1`(IN the_name VARCHAR(64),OUT
the_count INT)
BEGIN
SELECT COUNT(*) INTO the_count from employee where employeename=the_name;
END$$
DELIMITER ;
Use this example.
username and password are root and root for me. change as per your
requirement. Here i am counting the occurence of employeename="deepak"
import java.sql.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/test";
// Database credentials
static final String USER = "root";
static final String PASS = "root";
public static void main(String[] args) {
Connection conn = null;
CallableStatement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
String sql = "{call get_count_name1 (?, ?)}";
stmt = conn.prepareCall(sql);
//Bind IN parameter first, then bind OUT parameter
String name = "Deepak";
stmt.setString(1, name); // This would set ID as 102
// Because second parameter is OUT so register it
stmt.registerOutParameter(2, java.sql.Types.INTEGER);
//Use execute method to run stored procedure.
System.out.println("Executing stored procedure..." );
stmt.execute();
int count=stmt.getInt(2);
System.out.println(count);
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample

Categories

Resources