My program throws an error when I try to execute truncate query using JDBC java with sqlite.
import java.sql.*;
public class sqlTruncate {
public static void main( String args[] ) {
try{
Connection c = null;
Statement stmt = null;
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:Mail.db");
stmt = c.createStatement();
String sql = "TRUNCATE TABLE login";
stmt.executeUpdate(sql);
c.setAutoCommit(true);
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
}
}
Related
I am trying an example to return REFCURSOR using PGJDBC-NG Driver but getting an exception
java.lang.ClassCastException: java.lang.String cannot be cast to java.sql.ResultSet
at FunctionReturnRefCursor.main(FunctionReturnRefCursor.java:42)
Source/Code I am trying is -
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
public class FunctionReturnRefCursor {
public static void main(String[] args) throws Exception {
String createFunction = "CREATE OR REPLACE FUNCTION getUsers(mycurs OUT refcursor) "
+ " RETURNS refcursor "
+ " AS $$ "
+ " BEGIN "
+ " OPEN mycurs FOR select * from pg_user; "
+ " END; "
+ " $$ "
+ " LANGUAGE plpgsql";
String runFunction = "{? = call getUsers()}";
Class.forName("com.impossibl.postgres.jdbc.PGDriver");
try (Connection conn = DriverManager.getConnection(
"jdbc:pgsql://localhost:5432/test", "postgres", "password");
Statement statement = conn.createStatement();
CallableStatement cs = conn.prepareCall(runFunction);
) {
// We must be inside a transaction for cursors to work.
conn.setAutoCommit(false);
// create function
statement.execute(createFunction);
// register output
cs.registerOutParameter(1, Types.REF_CURSOR);
// run function
cs.execute();
// get refcursor and convert it to ResultSet
ResultSet resultSet = (ResultSet) cs.getObject(1);
while (resultSet.next()) {
System.out.println(resultSet.getString("usename"));
System.out.println(resultSet.getString("passwd"));
}
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Try this:
import java.sql.*;
public class FunctionReturnRefCursor {
public static void main(String[] args) {
String createFunction = "CREATE OR REPLACE FUNCTION getUsers(mycurs OUT refcursor) "
+ " RETURNS refcursor "
+ " AS $$ "
+ " BEGIN "
+ " OPEN mycurs FOR select * from pg_user; "
+ " END; "
+ " $$ "
+ " LANGUAGE plpgsql";
String runFunction = "{? = call getUsers()}";
//Substituted:
Driver driver = null;
try {
driver = new com.impossibl.postgres.jdbc.PGDriver();
DriverManager.registerDriver(driver);
} catch (SQLException e) {
e.printStackTrace();
}//:Substituted
try (Connection conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/test", "postgres", "password");
Statement statement = conn.createStatement();
CallableStatement cs = conn.prepareCall(runFunction);
) {
// We must be inside a transaction for cursors to work.
conn.setAutoCommit(false);
// create function
statement.execute(createFunction);
// register output
cs.registerOutParameter(1, Types.REF_CURSOR);
// run function
cs.execute();
// get refcursor and convert it to ResultSet
ResultSet resultSet = (ResultSet) cs.getObject(1);
while (resultSet.next()) {
System.out.println(resultSet.getString("usename"));
System.out.println(resultSet.getString("passwd"));
}
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I want to create an in-memory database and check that the table exists afterwards. Unfortunately, my code doesn't print anything to the console, so either the check for a table or the table creation process is wrong.
How do I fix it?
import java.sql.*;
public class Main {
private static String url = "jdbc:sqlite::memory";
private static void createNewTable(Connection conn) {
String sql = "CREATE TABLE IF NOT EXISTS students (\n"
+ " id integer PRIMARY KEY,\n"
+ " name text NOT NULL"
+ ");";
try (Statement stmt = conn.createStatement();) {
stmt.execute(sql);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
private static void checkTable(Connection conn){
String sql = "SELECT name FROM sqlite_temp_master WHERE type='table'";
try (Statement stmt = conn.createStatement();) {
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println("table: " + rs.getString(1));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
Connection conn;
try{
conn = DriverManager.getConnection(url);
createNewTable(conn);
checkTable(conn);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
public static void main(String[] argv) {
try {
createTable();
insertRecordIntoTable("leo","123");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
private static void createTable() throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
String sequence = "CREATE SEQUENCE ID_SEQ INCREMENT BY 1 MAXVALUE 99999999999999999999 MINVALUE 1 CACHE 20";
String createTableSQL = "CREATE TABLE DBUSER1("
+ "USER_ID NUMBER(5) NOT NULL, "
+ "USERNAME VARCHAR(20) NOT NULL, "
+ "PASSWORD VARCHAR(20) NOT NULL, "
+ "PRIMARY KEY (USER_ID) "
+ ")";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(createTableSQL);
System.out.println(createTableSQL);
// execute create SQL stetement
preparedStatement.executeUpdate(createTableSQL);
preparedStatement.executeUpdate(sequence);
System.out.println("Table \"dbuser\" is created!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
private static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(
DB_CONNECTION, DB_USER,DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
private static void insertRecordIntoTable(String username, String password) throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
String insertTableSQL = "INSERT INTO DBUSER1"
+ "(USER_ID, USERNAME, PASSWORD) VALUES"
+ "(ID_SEQ.NEXTVAL,?,?)";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(insertTableSQL);
// execute insert SQL stetement
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
preparedStatement.executeUpdate();
System.out.println("Record is inserted into DBUSER table!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
I cannot find the error when I try to create a sequence for my table.
When I try to insert some data in my table with the sequence it says it doesn't exist, but I did create it. Also I am not sure if i need a preparedStatement.setInt(1, seq_id.nextval); it gives an error but im not quite sure how I would do this
The solution might be adding the schema name (owner) before the name of sequence:
CREATE SEQUENCE some_nameOf_schema.ID_SEQ INCREMENT BY 1 MAXVALUE 99999999999999999999 MINVALUE 1 CACHE 20
You're preparing a statement with one SQL text, and executing the statement with two different SQL texts;
preparedStatement = dbConnection.prepareStatement(createTableSQL);
preparedStatement.executeUpdate(createTableSQL);
preparedStatement.executeUpdate(sequence);
...which is actually invalid according to the docs;
int executeUpdate(String sql)
throws SQLException
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.
Note:This method cannot be called on a PreparedStatement or CallableStatement.
What you need to do is to prepare and execute two different statements;
preparedStatement = dbConnection.prepareStatement(createTableSQL);
preparedStatement.executeUpdate();
preparedStatement = dbConnection.prepareStatement(sequence);
preparedStatement.executeUpdate();
In general, it doesn't make much sense to CREATE database objects every time your application starts up, because this is something that's usually done only once, when you install/upgrade the database/schema the application uses.
However, if you really have to do it this way, the current solution could be improved so that the following points are considered:
Only execute the CREATE statements when the objects do not yet exist in the DB. This can be done by first inspecting the USER_OBJECTS data dictionary view.
Use a plain Statement instead of PreparedStatement for executing the DDL (prepared statements are only useful for DML operations that use input variables)
Handle JDBC resources (Connection / Statement / ResultSet) concisely and safely through the try-with-resources construct
Here's how the code could look like:
// query constants
private static final String CHECK_DB_OBJECT =
"SELECT 1 FROM user_objects WHERE object_name = ?";
private static final String CREATE_SEQUENCE =
"CREATE SEQUENCE ID_SEQ INCREMENT BY 1 MAXVALUE 99999999999999999999" +
" MINVALUE 1 CACHE 20";
private static final String CREATE_TABLE = "CREATE TABLE DBUSER1("
+ "USER_ID NUMBER(5) NOT NULL, "
+ "USERNAME VARCHAR(20) NOT NULL, "
+ "PASSWORD VARCHAR(20) NOT NULL, "
+ "PRIMARY KEY (USER_ID) "
+ ")";
/* clip the main method etc. */
/**
* Creates the table and sequence only if they do not already exist.
*/
private static void createTableAndSequenceIfAbsent() {
try (Connection dbConnection = DriverManager.getConnection(
DB_CONNECTION, DB_USER, DB_PASSWORD);
PreparedStatement ps = dbConnection
.prepareStatement(CHECK_DB_OBJECT)) {
if (!dbObjectExists(ps, "ID_SEQ")) {
executeDDL(dbConnection, CREATE_SEQUENCE);
}
if (!dbObjectExists(ps, "DBUSER1")) {
executeDDL(dbConnection, CREATE_TABLE);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static boolean dbObjectExists(PreparedStatement ps,
String objectName) throws SQLException {
ps.setString(1, objectName);
ResultSet rs = ps.executeQuery();
// if the #CHECK_DB_OBJECT query returned a row, the object exists
return rs.next();
}
private static void executeDDL(Connection c, String sql)
throws SQLException {
try (Statement st = c.createStatement()) {
st.execute(sql);
}
}
I want to show progress in progress bar in java GUI, but the progress don't show anything until the process is done.
this is my try:
public void selectTweet(){
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = Drive
rManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
//menghitung jumlah query pada table tweet
String sql = "SELECT COUNT(*) FROM tweet";
ResultSet rs=stmt.executeQuery(sql);
int row = 0;
while(rs.next()){
row = rs.getInt("COUNT(*)");
}
int initial_number = Integer.parseInt(jTextField4.getText());
for(int i=initial_number;i<row;i++){
System.out.println("tweet ke-"+i);
String sql1 = "SELECT tweet,date,location FROM tweet WHERE tweet_id='"+i+"'";
ResultSet rs2 = stmt.executeQuery(sql1);
while(rs2.next()){
tweet = rs2.getString("tweet");
date = rs2.getString("date");
location = rs2.getString("location");
}
System.out.println("Tweet: " + tweet);
removeStopWords(tweet, i, date, location);
final int currentValue = i;
try{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
jProgressBar1.setValue(currentValue);
}
});
java.lang.Thread.sleep(100);
}catch (InterruptedException e) {
//JOptionPane.showMessageDialog(frame, e.getMessage());
}
}
}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)
conn.close();
}catch(SQLException se){}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
}
what i want to do is remove stopwords in string records from database, there are 5000 records, then i want to use progressbar to show the process, but it's not working. what i missed?, help me please.
You need to process your task in a separate Thread. If you don't, you block the main Swing thread in which the repaint method is called. Plus, I don't see any ProgressBar in your code, you must update its value when a step of the task have been performed.
SwingUtilities.invokeLater(
new Runnable(
public void run() {
for(int i=initial_number;i<row;i++){
System.out.println("tweet ke-"+i);
String sql1 = "SELECT tweet,date,location FROM tweet WHERE tweet_id='"+i+"'";
ResultSet rs2 = stmt.executeQuery(sql1);
while(rs2.next()){
tweet = rs2.getString("tweet");
date = rs2.getString("date");
location = rs2.getString("location");
}
System.out.println("Tweet: " + tweet);
removeStopWords(tweet, i, date, location);
jTextArea1.append(toTextArea);
// the JProgressBar must have been instantiated
// as new JProgressBar(initial_number,row - 1)
jProgressBar1.setValue(i);
}
}));
Using SwingWorker for long running tasks can make things easier.
public void selectTweet()
{
final int initial_number = Integer.parseInt(jTextField4.getText()); // This should be done outside of the worker because you are accessing a UI element's data.
SwingWorker<Void, int[]> worker = new SwingWorker<Void, int[]>()
{
#Override
protected Void doInBackground() throws Exception
{
Connection conn = null;
Statement stmt = null;
try
{
Class.forName( "com.mysql.jdbc.Driver" );
conn = DriverManager.getConnection( DB_URL, USER, PASS );
stmt = conn.createStatement();
String sql = "SELECT COUNT(*) FROM tweet";
ResultSet rs = stmt.executeQuery( sql );
int row = 0;
while( rs.next() )
{
row = rs.getInt( "COUNT(*)" );
}
for( int i = initial_number; i < row; i++ )
{
System.out.println( "tweet ke-" + i );
String sql1 = "SELECT tweet,date,location FROM tweet WHERE tweet_id='" + i + "'";
ResultSet rs2 = stmt.executeQuery( sql1 );
String tweet, date, location;
while( rs2.next() )
{
tweet = rs2.getString( "tweet" );
date = rs2.getString( "date" );
location = rs2.getString( "location" );
}
System.out.println( "Tweet: " + tweet );
removeStopWords( tweet, i, date, location );
publish( new int[]{i,row} );
}
}
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 )
conn.close();
}
catch( SQLException se )
{
}// do nothing
try
{
if( conn != null )
conn.close();
}
catch( SQLException se )
{
se.printStackTrace();
}//end finally try
}//end try
}
#Override
protected void process( List<int[]> chunks ) // Run in the EDT, so no invokeLater needed
{
if( chunks == null || chunks.isEmpty() )
return;
int[] last = chunks.get( chunks.size() - 1 );
jProgressBar1.setMinimum( 0 );
jProgressBar1.setMaximum( last[1] - initial_number );
jProgressBar1.setValue( last[0] - initial_number );
}
#Override
protected void done() // Run in the EDT, so no invokeLater needed
{
jProgressBar1.setValue( jProgressBar1.getMaximum() );
}
};
worker.execute();
}
I am trying to inserting the data into the table using ms access 2007 but getting the exception "java.sql.SqlException: no data found"
My data souce name is employee
import java.sql.*;
class AccessDatabase
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection ("jdbc:odbc:employee");
Statement st = con.createStatement();
String name = "roseindia";
String address = "delhi";
int i = st.executeUpdate("insert into user(name,address) values
('" + name + "','" + address + "')");
System.out.println("Row is added");
}
catch (Exception e)
{
System.out.println(e);
}
}
}
I think you don't have a database created. Following code should work:
import java.sql.*;
class ExecuteSqlQuery {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
Statement st=con.createStatement();
String str = "CREATE TABLE user(id INTEGER, " + "name VARCHAR(25), address VARCHAR(100), primary key(id))";
st.executeUpdate(str);
System.out.println("Table is created into the database.");
st.executeUpdate("insert into user(id,name,address) values(1111,'roseindia','Rohini,Delhi')");
System.out.println("Row is inserted.");
st.close();
con.close();
}
catch (Exception ex) {
System.out.println("Unable to connect to database.");
}
}
}