java,database,sqlite , PreparedStatement.executeUpdate() doesn't insert in sqlite database

PreparedStatement.executeUpdate() doesn't insert in sqlite database


Tag: java,database,sqlite

i'm trying to make a DAO class for my Java project. I've a SQLite Database with only one table "USER". The schema is:

total_matches INTEGER DEFAULT 0,
victories INTEGER DEFAULT 0,
times_alien INTEGER DEFAULT 0,
times_human INTEGER DEFAULT 0,
total_steps INTEGER DEFAULT 0,
humans_killed INTEGER DEFAULT 0,
aliens_killed INTEGER DEFAULT 0,
kills_as_human INTEGER DEFAULT 0,
kills_as_alien INTEGER DEFAULT 0,
total_escapes INTEGER DEFAULT 0,
total_broken_hatches INTEGER DEFAULT 0,
total_noises INTEGER DEFAULT 0,
online_status VARCHAR(5) NOT NULL DEFAULT "false");

My UserDAOImpl class has findAll(), findByNickname(String nickname), insert, update, delete methods.

I use PreparedStatementto prevent SQL Injection.

My Issue is that if I call my insert(User toInsert) method and then cycle through the findAll() result, I can see the right insertion.

But if I go to the Terminal and open the DB with the SQLite command line, when I execute "SELECT * FROM USER", the previous insertion doesn't shows.

The DB Class:

 * The Class DB.
 * Gives a connection to the game Database.
public class DB {

/**  the singleton instance of the Database. */
    private static DB instance = new DB();

    /**  the path to the database. */
    private static final String DBPath = "db/eftaios_DB.db";

     * Istantiates a new Database.
    private DB(){

     * Create a connection between this class and the database files.
     * @return the database connection.
     * @throws SQLException the SQL exception
    public Connection connect() throws SQLException{
        Connection dbConnection = null;
        try {

            String dbPath = DB.class.getClassLoader().getResource(DBPath).getPath();
            dbConnection = DriverManager.getConnection("jdbc:sqlite:"+dbPath);

        } catch (ClassNotFoundException e) {
             * do nothing, the class is imported in the maven dependencies
        } catch (SQLException e) {
            throw new SQLException();
        return dbConnection;

The DAO Class is:

 * The class UserDAOImpl implements the UserDAOInterface
 * It implements a DAO (Data Access Object) for the User table.
 * It gives access to the User table on the Database.
 * With this class you can perform queries like find, insert, delete and update on the USER table.
public class UserDAOImpl implements UserDAOInterface {

    /**  the database connection used to query it. */
    private Connection dbConnection;

    /**  the result of a query to the database. */
    private ResultSet queryResult;

    /**  the statement to execute to perform db queries. */
    private Statement queryStatement;

    /**  the prepared statement to execute mysql injection secure queryes. */
    private PreparedStatement queryPreparedStatement;

    /**  the name of the database user's table. */
    private static final String USER_TABLE = "USER";

     * To user list.
     * @param qryResult the qry result
     * @return the list
     * @throws SQLException the SQL exception
    private List<User> toUserList(ResultSet qryResult) throws SQLException{
        List<User> result = new ArrayList<User>();
        /* forall user in result, populate the new user and add it to the users list */
            User record = new User();
        return result;

     * (non-Javadoc)
     * @see it.polimi.ingsw.deolacremona.server.model.database.UserDAOInterface#findAll()
    public List<User> findAll() throws SQLException {

        String findAllQuery = "SELECT * FROM "+USER_TABLE;

        List<User> users = new ArrayList<User>();
        this.dbConnection   = DB.getDatabase().connect();
        this.queryStatement = this.dbConnection.createStatement();
        this.queryResult    = this.queryStatement.executeQuery(findAllQuery);

        users = this.toUserList(queryResult);

        return users;

     * (non-Javadoc)
     * @see it.polimi.ingsw.deolacremona.server.model.database.UserDAOInterface#findByNickname(java.lang.String)
    public List<User> findByNickname(String userNickname) throws SQLException {

        String findByNicknameQuery = "SELECT * FROM "+USER_TABLE+" WHERE "+User.NICKNAME_COL_NAME+"=?";

        List<User> users = new ArrayList<User>();
        this.dbConnection = DB.getDatabase().connect();

        /* preparing the statement to prevent sql injection */
        this.queryPreparedStatement = this.dbConnection.prepareStatement(findByNicknameQuery);
        this.queryPreparedStatement.setString(1, userNickname);

        /* now get the result */
        this.queryResult = this.queryPreparedStatement.executeQuery();

        users = this.toUserList(queryResult);


        return users;

     * (non-Javadoc)
     * @see it.polimi.ingsw.deolacremona.server.model.database.UserDAOInterface#insert(it.polimi.ingsw.deolacremona.server.model.database.User)
    public boolean insert(User toInsert) throws SQLException {

            boolean result = false;
            MD5Hasher hasher = new MD5Hasher();
            String md5Password = hasher.md5(toInsert.getPassword());

            String insertQuery = 

                    "INSERT INTO "+USER_TABLE+" ("+User.NICKNAME_COL_NAME+","+User.PASSWORD_COL_NAME+") VALUES (?,?)";

            this.dbConnection = DB.getDatabase().connect();

            /* preparing the statement to prevent sql injection */
            this.queryPreparedStatement = this.dbConnection.prepareStatement(insertQuery);
            this.queryPreparedStatement.setString(1, toInsert.getNickname());
            this.queryPreparedStatement.setString(2, md5Password);

                result = true;


            return result;

     * (non-Javadoc)
     * @see it.polimi.ingsw.deolacremona.server.model.database.UserDAOInterface#update(it.polimi.ingsw.deolacremona.server.model.database.User)
    public boolean update(User toUpdate) throws SQLException {
        boolean result = false;

        String updateQuery = "UPDATE "+USER_TABLE+" SET "
                + User.ALIENS_KILLED_COL_NAME        +"=?,"
                + User.HUMANS_KILLED_COL_NAME        +"=?,"
                + User.KILLS_AS_ALIEN_COL_NAME       +"=?,"
                + User.KILLS_AS_HUMAN_COL_NAME       +"=?,"
                + User.ONLINE_STATUS_COL_NAME        +"=?,"
                + User.TIMES_ALIEN_COL_NAME          +"=?,"
                + User.TIMES_HUMAN_COL_NAME          +"=?,"
                + User.TOTAL_BROKEN_HATCHES_COL_NAME +"=?,"
                + User.TOTAL_ESCAPES_COL_NAME        +"=?,"
                + User.TOTAL_MATCHES_COL_NAME        +"=?,"
                + User.TOTAL_NOISES_COL_NAME         +"=?,"
                + User.TOTAL_STEPS_COL_NAME          +"=?,"
                + User.VICTORIES_COL_NAME            +"=?"
                + " WHERE "+User.NICKNAME_COL_NAME+"=?";

        /* preparing the sql statement to prevent sql injection */
        this.dbConnection = DB.getDatabase().connect();
        this.queryPreparedStatement = this.dbConnection.prepareStatement(updateQuery);
        this.queryPreparedStatement.setInt    (1, toUpdate.getAliensKilled());
        this.queryPreparedStatement.setInt    (2, toUpdate.getHumansKilled());
        this.queryPreparedStatement.setInt    (3, toUpdate.getKillsAsAlien());
        this.queryPreparedStatement.setInt    (4, toUpdate.getKillsAsHuman());
        this.queryPreparedStatement.setBoolean(5, toUpdate.isOnlineStatus());
        this.queryPreparedStatement.setInt    (6, toUpdate.getTimesAlien());
        this.queryPreparedStatement.setInt    (7, toUpdate.getTimesHuman());
        this.queryPreparedStatement.setInt    (8, toUpdate.getTotalBrokenHatches());
        this.queryPreparedStatement.setInt    (9, toUpdate.getTotalEscapes());
        this.queryPreparedStatement.setInt    (10, toUpdate.getTotalMatches());
        this.queryPreparedStatement.setInt    (11, toUpdate.getTotalNoises());
        this.queryPreparedStatement.setInt    (12, toUpdate.getTotalSteps());
        this.queryPreparedStatement.setInt    (13, toUpdate.getVictories());
        this.queryPreparedStatement.setString (14, toUpdate.getNickname());

            result = true;

        return result;

     * (non-Javadoc)
     * @see it.polimi.ingsw.deolacremona.server.model.database.UserDAOInterface#updateAdder(it.polimi.ingsw.deolacremona.server.model.database.User)
    public boolean updateAdder(User toUpdate) {
        // TODO Auto-generated method stub
        return false;

     * (non-Javadoc)
     * @see it.polimi.ingsw.deolacremona.server.model.database.UserDAOInterface#delete(it.polimi.ingsw.deolacremona.server.model.database.User)
    public boolean delete(User toDelete) throws SQLException {

        boolean result = false;

        String deleteQuery = "DELETE FROM "+USER_TABLE+" WHERE username=?";

        this.dbConnection = DB.getDatabase().connect();

        this.queryPreparedStatement = this.dbConnection.prepareStatement(deleteQuery);
        this.queryPreparedStatement.setString(1, toDelete.getNickname());

            result = true;


        return result;

My test main method is:

public static void main(String[] args) throws SQLException, UnknownHostException{
        DB database = DB.getDatabase();

        MD5Hasher h = new MD5Hasher();

        UserDAOImpl d = new UserDAOImpl();

        User s = new User();

//      d.delete(s);

        for(User x : d.findAll()){
            System.out.println("Nickname: "+x.getNickname()+" password: "+x.getPassword()+" matches: "+x.getTotalMatches());

Thank you for your time.

EDIT: when I cut the database and put it into another directory, exit eclipse, move back the database in his previous directory and reopen eclipse, then all the changes that Java done previously are lost. –


SOLVED: In a Maven Project, all the resources are copied into another directory after the "build" command. I was reading the wrong db.


Join files using Apache Spark / Spark SQL

I am trying to use Apache Spark for comparing two different files based on some common field, and get the values from both files and write it as output file. I am using Spark SQL for joining both files (after storing the RDD as table). Is this the correct approach?...

viewResolver with more folders inside of WEB-INF/jsp is not working in spring

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <!-- avoid '???' --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp"/> </bean> if i create other subfolders under jsp , for instance /WEB-INF/jsp/reports , /WEB-INF/jsp/insertions how should i configure now the viewResolver to can resolve these new sub folders??...

Unfortunately, (My app) has stopped. Eclipse Android [duplicate]

This question already has an answer here: What is a Null Pointer Exception, and how do I fix it? 12 answers I'm a beginner in android developing and I'm trying to build a simple app but I'm getting this error in the emulator.(Unfortunately,(App) has unexpectedly stopped). LogCat package...

Android set clickable text to go one fragment to another fragment

I need to do something like this. Suppose I have 2 fragments A and B.There is a text which can be clickable in fragment A and when user click this text , he can go to fragment B. This example helped me to do it but I think it does...

Why am getting this error?: Unknown column 'firstname' in 'field list'

if(isset($_POST["submit"])) { // Details for inserting into the database $id = htmlentities($_POST["id"]); $firstname = htmlspecialchars($_POST["firstname"]); $lastname = htmlspecialchars($_POST["lastname"]); $username = htmlspecialchars($_POST["username"]); $password = htmlspecialchars($_POST["password"]); // Dealing with inserting $query = "INSERT INTO `myDatabaseForAll`.`users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES (NULL, $firstname, $lastname,$username,$password)"; $result = mysqli_query($connection,$query);...

Mysterious claim of a missing { in eclipse

I have a case of a mysterious missing curly brace that I don't see any use for. Eclipse says, "Syntax error on token ";", { expected after this token". Either I am missing something very silly or there is something new I have to learn about Java. This is the...

Interpreting hex dump of java class file

I understand the structure of a java .class file, but when I want to interpret the raw hex data I get a bit lost. This is a hex dump of a class file, excluding the header and constant pool. I understand the header to be the magic number, minor_version and...

type conversion if flex

I am using Flerry as Java-Flex bridge for my Flex Desktop Application. How to convert List in Java to ArrayCollection in Flex Flex Code:- [Bindable]public var screenList:ArrayCollection; <flerry:NativeObject id="windowControllerObj" source="ls.window.EnumAllWindowNames" singleton="true" fault="windowControllerObj_faultHandler(event)"> <flerry:NativeMethod id="getWindowNames" name="getAllWindowNames" result="windowControllerObj_resultHandler(event)" fault="getWindowNames_faultHandler(event)"/>...

WebDriver can't get dropdown menu element (Java)

I write a script on Java for Selenium WebDriver, and I have a problem with selected from dropdown menu. Here's my locator: new Select(driver.findElement("FormElement_select_68_input_input"))).selectByVisibleText("Image"); Here's an error: Here's HTML code: Need to select "Image" from this menu, but have an error. Before I had the error like this,...

Logging operations in lightadmin

I have a Java web application which use Spring and Hibernate and I plan to use lightadmin to provide an administration interface. However, I found very little information about the logging part of lightadmin : if I have such an adminsitration interface, I would like that any operation made to...

Using world coordinates

I am currently using pixels as units for placing objects within my world, however this can get tedious because I only ever place objects every 16 pixels. For example, I would like to be able to place an object at position 2 and have the object rendered at the pixel...

Get the value of the last inserted record

I am trying to get the stop_name of the last inserted row in the table with preparedStatement. How can I get the last inserted one? I appreciate any help. behavoiur table: CREATE TABLE IF NOT EXISTS behaviour( behaviour_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, mac VARCHAR(30) NOT NULL, stop_name VARCHAR(30)...

@RestController throws HTTP Status 406

I am working on a basic Hello World program using Spring and Restful webservices. But when I try to call my service I am getting below error message: HTTP Status 406 - description - The resource identified by this request is only capable of generating responses with characteristics not acceptable...

custom arraylist get distinct

is there any way to get the distinct values of a custom arraylist? public class mystatistic extends BaseActivity { public String objectid; public String playerid; public String playername; public String enemyid; public String enemyname; public String question; public mystatistik(String objectid, String playerid, String playername, String enemyid, String enemyname, String question)...

Get current latitude and longitude android

Requirement: 1.Sometimes(not everytime) I am getting latitude and longitude 0.0. 2.I want to know how to get the location update after user has enabled the gps from the settings. Here is my code public class GPSTracker extends Service implements LocationListener { private final Context mContext; // flag for GPS status...

How to call MySQL view in Struts2 or Hibernate

I have a view in MySQL database CREATE VIEW CustInfo AS SELECT a.custName, a.custMobile, b.profession, b.companyName, b.annualIncome FROM customer a INNER JOIN cust_proffessional_info b ON a.cust_id=b.cust_id Is there any way that i can call this view using Struts2 or in Hibernate. I have tried to search it but could not...

Reading and modifying the text from the text file in Java

I am have a project that need to modify some text in the text file. Like BB,BO,BR,BZ,CL,VE-BR I need make it become BB,BO,BZ,CL,VE. and HU, LT, LV, UA, PT-PT/AR become HU, LT, LV, UA,/AR. I have tried to type some code, however the code fail to loop and also,in this...

Can I install 2 or more Android SDK when using Eclipse

I am new to android developments. I am setting up my android development environment using Eclipse. I have a test smart phone with Android version 4.2.2. The automatic installation installed the latest Android SDK version, which is 5.1.1. My questions are: 1. Do I have to install the SDK version...

Get network interfaces on remote machine

I know in java we can do NetworkInterface.getNetworkInterfaces() to get all available network interfaces on local machine. Can we do similar thing where I can pass host name to get the NICs(with IPs) which are up and running?

Form submit portlet with Spring MVC

I'm trying to achieve a Liferay portlet of submit form using spring MVC. The model: package com.model; public class Person { String firstName; String middleName; public String getFirstName() { return this.firstName; } public String getMiddleName() { return this.middleName; } public void setFirstName(String firstName) { this.firstName=firstName; } public void setMiddleName(String middleName)...

Numeric literals in Java - octal? [duplicate]

This question already has an answer here: How does a leading zero change a numeric literal in Java? 3 answers Here is some code in java on datatypes: class Test { public static void main(String args[]) { int i = -0777; System.out.println(i); } } The output of the above...

Foreign key in C#

I have two tables, A and B, in a dataset in SQL Server; I have created a connection to the dataset in a c# project in visual studio. How can I create a foreign key ( A is the parent) between my two tables ? I want to create the...

error: cannot find symbol class AsyncCallWS Android

I'm trying to rewrite the application in this, in Android Studio link, which is written in Eclipse. There are two problems, first problem is there is this line in the project : import com.example.webserviceactivity.R; I couldn't write this one on Android Studio. The second problem is, in this part of...

Get document on some condition in elastic search java API

As I know we can parse document in elastic search, And when we search for a keyword, It will return the document using this code of java API:- searchHits = node.client() .prepareSearch() .setIndices("indices") .setQuery(qb) .setFrom(0).setSize(1000) .addHighlightedField("file.filename") .addHighlightedField("content") .addHighlightedField("meta.title") .setHighlighterPreTags("<span class='badge badge-info'>") .setHighlighterPostTags("</span>") .addFields("*", "_source")...

Finding embeded xpaths in a String

I have a string where I have the user should be able to specify xpaths that will be evaluated at runtime. I was thinking about having a the following way to specify it. String = "Hi my name is (/message/user) how can i help you with (/message/message) "; How can...

What type of database is the best for storing array or object like data [on hold]

I'm just curious what the best method would be if I'm trying to have a bot running on my Node server that I could play Blackjack against. But for multiple connected clients via sockets, each connected socket will have their own bot to play against but I need some way...

How to block writes to standard output in java (System.out.println())

In Java, how to block code from writing to system out? My app calls a 3rd party library that spams logs by issuing numerous System.out.println() calls. I don't have legal rights to decompile and patch the library. I'm running Websphere 8.5.x Considered using System.setOut(PrintStream out), but that will effect the...

Java Scanner not reading newLine after wrong input in datatype verification while loop

I've looked at similar questions and tried to follow the answers that solved the issues that others have had but putting the or sc.nextLine() after the while loop causes it to go into an infinite loop. The problem is if a user enters incorrect input (nothing or a number)...

SOAP Client, Following an example

I need to consume a SOAP Server named "Mouser" for my company. However I have a problem when I try to send a message. The documentation of my request is : POST /service/searchapi.asmx HTTP/1.1 Host: Content-Type: application/soap+xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <soap12:Envelope xmlns:xsi="" xmlns:xsd="" xmlns:soap12=""> <soap12:Header> <MouserHeader...

setOnClickListener error Null object

I saw many questions like mine and I try to fix my codes but failed... this is my code: public class MainActivity extends ActionBarActivity { EditText usernameEditText; EditText passwordEditText; public Button saveme; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); usernameEditText = (EditText) findViewById(; passwordEditText = (EditText) findViewById(; saveme = (Button)...

PropertyNotFoundException in jsp

Am getting this error in my application javax.el.PropertyNotFoundException: Property 'survey_id' not found on type com.moh.forms.MOH731 javax.el.BeanELResolver$BeanProperties.get( javax.el.BeanELResolver$BeanProperties.access$400( javax.el.BeanELResolver.getValue( This is my @Id @GeneratedValue(strategy = GenerationType.AUTO) private int survey_id; public MOH731 (int survey_id, String uname)...

BitmapFont class does not have getBound(String) method

Previously I used getBound method for BitmapFont class in libgdx, but now, I am unable to use it. I cannot find the changes in latest version. Any help is appreciated. Thank you...

count items in a column vaadin

Good day everyone! How do I get the number of items that a column contains? I want to hide the "Workgroup" column if it's empty, I just don't know how. Table tblTeachings = new Table(); tblTeachings.addContainerProperty("#", Integer.class,0); tblTeachings.addContainerProperty("Course",String.class,""); tblTeachings.addContainerProperty("Teaching name",String.class,""); tblTeachings.addContainerProperty("Start date",String.class,""); tblTeachings.addContainerProperty("End Date",String.class,""); tblTeachings.addContainerProperty("Activity...

Android String if-statement

I have a if-statement in the start of my app if (ready.equals("yes")){ ... } and later on my code I have ready="yes"; but the if statement is never called, why? The ready="yes"; is called from a background thread, is that why? public void DownloadFromUrl(final String fileName) { //this is the...

App Not Downloading Newest Version Of File [Java]

Okay, I've been trying to figure this out for a few hours and it's starting to kill me. I wrote a primitive version checker for an app I work on every once and awhile. It's just a simple for fun project. The version checker has been a pain though. It...

Pull information from SQL database and getting login errors

I am creating a very small, simple CRM for a company, they require the function to be able to view the last 25 orders via the dashboard. The orders are added via a Order-add form within the CRM. When adding the following code to the CRM I get an error:...

How to check if an ExecutionResult is empty in Neo4j

I am executing a query in neo4j using java. I don't know how to check if the execution result is empty. Here is my code. String firstquery=" start n=node(*) match(b)-[relatedto]->(n) where b.value=\""+applicationName+"\" return n"; ExecutionResult execResult = execEngine.execute(firstquery); System.out.println("executing query"); String results = execResult.dumpToString(); System.out.println(results); Iterator<Node> n_column1 = execResult.columnAs( "n"...

Selenium catch popup on close browser

I'm trying to test that when I close my window a popup shows with a warning message. I've tried both driver.close() and driver.quit() after making sure I'm on the proper window but this just terminates the process since my popup doesn't show. I could test it by using the awt...

Get element starting with letter from List

I have a list and I want to get the position of the string which starts with specific letter. I am trying this code, but it isn't working. List<String> sp = Arrays.asList(splited); int i2 = sp.indexOf("^w.*$"); ...

If I export my database with phpmyadmin will it lock my tables or take my database down?

I want to create a backup of my database using the phpmyadmin export function. the database can't have any down time so I need to know if running a database export will take the database down? I've looked on-line but all I get is instructions on how to export. No...

Android Implicit Intent for Viewing a Video File

In my Android app, I have a button that when clicked, launches the external application of my choice to play a video (I gather that this is called an "implicit intent"). Here is the relevant Java code from my onCreate method. Button button = (Button) findViewById(; button.setOnClickListener ( new Button.OnClickListener()...

Javadoc: Do parameter and return need an explicit type description

When Javadoc'ing, I don't know whether you should explicitly say whether the parameters are of type String or int. For example /** * This method does something * @param foo an object of type Foo * @param abc the number of doors, of type int * @return the number of...

MySQL: Select several rows based on several keys on a given column

I have this mysql table structure: ------------------------------------ | item_id | meta_key | meta_value | ------------------------------------ 159 category Bungalow 159 location Lagos 159 price 45000 160 category Bungalow 160 location Abuja 160 price 53500 ... 350 category Bungalow 350 location Lagos 350 price 32000 What I'd like to do is select...

Bulkheading strategies for Akka actors

I have a scenario where an important actor needs to make a call to a slow (15 - 20 seconds) remote system: // Non-actor code equivalent public Result makeSlowNetworkCall(Request request) { Result result = slowServiceClient.soooooSlow(request); // Could be up to 15 - 20 SECONDS (mehhhh) return result; } The Akka...

how to call Java method which returns any List from R Language? [on hold]

How to call java method which returns list from R Language.

How to do custom rounding of numbers in Java?

Suppose I want to round numbers that have mantissa greater than 0.3 'up' and those below 'down'. How can I do it in Java? The only thing that came to my mind was Math.round(), but I can't seem to make it follow a certain rule....

why java API prevents us to call add and remove together?

As per Java API- IllegalStateException - if neither next nor previous have been called, or remove or add have been called after the last call to next or previous remove()- Removes from the list the last element that was returned by next() or previous() (optional operation). This call can only...

How can implement long running process in spring hibernate?

as we know the struts interceptor execute and wait will take care of long running process by not getting the request to timeout and destroy it sends wait and at last the desired response i want to implement the same for long running process in spring and hibernate. Thanks....

Java dice roll with unexpected random number

I've written a simple Java program to display the results of 20 dice rolls on the console. The results I'm getting are listed below: 3 1 [email protected] 1 5 4 1 [email protected] 1 [email protected] [email protected] 1 6 [email protected] 1 [email protected] [email protected] 1 2 3 3 When I ran it for...

Getting particular view from expandable listview

In my list view I have an textview in expandable group and I want to open the dialog when textview is clicked to fill the information through edittext and update textview. Problem: how could I get the groupview textview item in my fragment oncreateview() method....