Posts Tagged ‘technology’

The Java programming language is a strongly-typed language and it consist of eight primitive data types (byte, short, int, long, float, double, boolean, char). For more about java primitive data type, please visit http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html

Well, sometime we really need to know what is the limit of the primitive types in java. With following simple code, we can print out the limit of each of the java primitive data types (except boolean and char) 🙂

public class PrintTypeLimit
{
    public static void main(String args[]) {        System.out.println("Min byte value   = " + Byte.MIN_VALUE);
        System.out.println("Max byte value   = " + Byte.MAX_VALUE);
        System.out.println("Min short value  = " + Short.MIN_VALUE);
        System.out.println("Max short value  = " + Short.MAX_VALUE);
        System.out.println("Min int value    = " + Integer.MIN_VALUE);
        System.out.println("Max int value    = " + Integer.MAX_VALUE);
        System.out.println("Min long value    = " + Long.MIN_VALUE);
        System.out.println("Max long value    = " + Long.MAX_VALUE);
        System.out.println("Min float value  = " + Float.MIN_VALUE);
        System.out.println("Max float value  = " + Float.MAX_VALUE);
        System.out.println("Min double value = " + Double.MIN_VALUE);
        System.out.println("Max double value = " + Double.MAX_VALUE);
    }
}

 

Output

Min byte value   = -128
Max byte value   = 127
Min short value  = -32768
Max short value  = 32767
Min int value    = -2147483648
Max int value    = 2147483647
Min long value    = -9223372036854775808
Max long value    = 9223372036854775807
Min float value  = 1.4E-45
Max float value  = 3.4028235E38
Min double value = 4.9E-324
Max double value = 1.7976931348623157E308

 

Do you think this is possible to do? but i think possible,there are various lot of recovery tools in the internet to download,but all of them are not surely work 100% like you are expected.but there is a recovery tool name recuva,working perfectly as you expected. Download recuva here
Okey now we can see the step by steps to start the process.
Step1)-insert the pen drive in to the usb port.wait for some moment to identify .after that right click on the pen drive icon in the computer and scan for recovery of bad sector and automatically fix system errors

Note- above step is important to recover correctly
Step2)- install the recuva recovery software before you downloaded.
Step3)- open the tool by clicking its icon on the desktop. Program will open up.

Step4)- if you recover images tick the dot on pictures ( removable disk /memory device ) and then select deep scan

Note- selecting deep scan is important.

Step5)-click scan .scanning process will start up wait for some hours or minutes .that depending on your pen drive volume.
Step6)-now picture list show up ,you must select the picture you want. click recover and select the location to put the pictures

That’s all enjoy

Power Walking energy floorIn the sustainable energy market, Energy Floors, a Netherlands-based firm is trying hard to make its place. They sell products like Sustainable Energy Floor and Sustainable Dance Floor, that convert footsteps into electricity. As soon as anyone steps onto the floor, the tile flexes round about 10mm, and that movement is converted into electricity-15 Watts on average, and up to 25 Watts peak. If the tiles are connected together, 40 to be precise, the network can produce up to 1kW and this is possible due to the modular nature of these tiles.Power Walking energy floor 2Although we do not know how these magnificent tiles are made but for what we know is that it’s not piezoelectric. For what we can see, it looks like a rack-and-pinion that drives a small permanent magnet generator.

The flow of electricity is directed by a controller module. Charging low voltage devices, charging batteries, or lighting pathways with LEDs is all that can be done from the 12V output.

Power Walking energy floor4When you step on the blocks, they light up and this intrigues people to step on them again. Thus it would be an attractive marketing technique too.

As much fun as they may sound, these aren’t a techie joke or a high-tech toy. Russian Railway Research Institute has partnered with them and hopes to put Energy Floors on railroad platforms and high-traffic walkways. They also plan on looking into the use of this technology in order to gain energy from the movement of cars and trains.

Interesting fact, apart from the company’s sustainable focus, not only are the floor tiles made out of recyclable materials but has an expected lifetime of 30years.

Power Walking energy floor3Laurence Kemball-Cook delivers a TED talk on this concept:

‘Sustainable energy is a multifaceted industry. Solar, wind, and hydroelectric are the big players, but small energy-harvesting products have their place as well. A journey of a thousand miles begins with a single step. Energy Floors could make that step more productive.’

 

This tutorial about Hide and Seek with jQuery and PHP. This script helps you to present all modules in single page. Take a look at live demo click buttons

 


Download Script     Live Demo

Javascript Code

// <![CDATA[
javascript” src=”http://ajax.googleapis.com/ajax/
// ]]>
libs/jquery/1.3.0/jquery.min.js”>
<script type=”text/javascript”>
$(function()
{

$(“.button”).click(function()
{
var button_id = $(this).attr(“id”);

//Add Record button

if(button_id==”add”)
{
$(“#results”).slideUp(“slow”);
$(“#save_form”).slideDown(“slow”);
}

//Cancel button

else if(button_id==”cancel”)
{
$(“#save_form”).slideUp(“slow”);
$(“#results”).slideDown(“slow”);
}

// save button
else

{

// insert record
// more details Submit form with jQuery

}

return false;

});
});
</script>

HTML Code
Contains javascipt code. $(“.button”).click(function(){}- button is the class name of buttons(Add, Save and Cancel). Using $(this).attr(“id”) calling button id value.

<div id=”results” >

<a href=”#”color: blue;”>button” id=”add” >Add Record </a>
</div>

<div id=”save_form” style=”display:none” >

<a href=”#”color: blue;”>button” id=”save” >Save </a>
<a href=”#”color: blue;”>button” id=”cancel” >Cancel </a>
</div>

<div id=”update” >

</div>
I received lot of requests from my readers that asked to me how to implement Pagination with jQuery, PHP and MySQL. so I had developed a simple tutorial. It’s looks big but very simple script. Take a look at this live demo
Pagination with jQuery, MySQL and PHP.


The tutorial contains three PHP files and two js files includes jQuery plugin.

-config.php (Database Configuration)
-pagination.php
-pagination_data.php
-jquery.js
-jquery_pagination.js

Download Script     Live Preview

Database Table

CREATE TABLE messages
(
msg_id INT PRIMARY KEY AUTO_INCREMENT,
message TEXT
);
 

jquery_pagination.js
Contains javascript this script works like a data controller.

$(document).ready(function()
{

//Display Loading Image

function Display_Load()
{
$(“#loading”).fadeIn(900,0);
$(“#loading”).html(“<img src=”bigLoader.gif” />”);
}

//Hide Loading Image

function Hide_Load()
{
$(“#loading”).fadeOut(‘slow’);
};

//Default Starting Page Results

$(“#pagination li:first”)
.css({‘color’ : ‘#FF0084’}).css({‘border’ : ‘none’});
Display_Load();
$(“#content”).load(“pagination_data.php?page=1”, Hide_Load());

//Pagination Click

$(“#pagination li”).click(function(){
Display_Load();

//CSS Styles

$(“#pagination li”)
.css({‘border’ : ‘solid #dddddd 1px’})
.css({‘color’ : ‘#0063DC’});

$(this)
.css({‘color’ : ‘#FF0084’})
.css({‘border’ : ‘none’});

//Loading Data

var pageNum = this.id;
$(“#content”).load(“pagination_data.php?page=” + pageNum, Hide_Load());
});

});

config.php
You have to change hostname, username, password and databasename.

<!–?php

$mysql_hostname = “localhost”;
$mysql_user = “username”;
$mysql_password = “password”;
$mysql_database = “database”;
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die(“Opps some thing went wrong”);
mysql_select_db($mysql_database, $bd)
or die(“Opps some thing went wrong”);

?>

pagination.php
User interface page.

<?php

include(‘config.php’);
$per_page = 9;

//Calculating no of pages
$sql = “select * from messages”;
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$pages = ceil($count/$per_page)

?>

// <![CDATA[
javascript” src=”http://ajax.googleapis.com/ajax/
// ]]>
libs/jquery/1.3.0/jquery.min.js”>
// <![CDATA[
javascript” src=”jquery_pagination.js”>
// ]]>

<div id=”loading” ></div>
<div id=”content” ></div>
<ul id=”pagination”>
<?php
//Pagination Numbers

for($i=1; $i<=$pages; $i++)
{
echo ‘<li id=”‘.$i.‘”>’.$i.‘</li>’;
}

?>
</ul>

pagination_data.php
Simple php script display data from the messages table.

<?php

include(‘config.php’);
$per_page = 9;
if($_GET)
{
$page=$_GET[‘page’];
}

$start = ($page-1)*$per_page;
$sql = “select * from messages order by msg_id limit $start,$per_page”;
$result = mysql_query($sql);

?>

<table width=”800px”>

<?php

while($row = mysql_fetch_array($result))
{
$msg_id=$row[‘msg_id’];
$message=$row[‘message’];

?>

<tr>
<td><?php echo $msg_id; ?></td>
<td><?php echo $message; ?></td>
</tr>

<?php

}

?>

</table>

CSS Code
CSS code for page numbers.

#loading

{
width: 100%;
position: absolute;
}

li

{
list-style: none;
float: left;
margin-right: 16px;
padding:5px;
border:solid 1px #dddddd;
color:#0063DC;
}

li:hover

{
color:#FF0084;
cursor: pointer;
}

Reference: 9lessons.info

English: Logo of Apache Struts

Apache Struts has changed the way we develop a Web application. Since its inception as an MVC architecture, Struts has been extensively used in J2EE world to develop robust, extendable and effective web applications.

Introduction to Struts Validation Framework

One of the important features of Struts framework is Struts Validation framework that performs validation on incoming form data. Validation framework was introduced by David Winterfeldt as an external plugin to Struts framework. It’s functionality has since been split so that validator can serve as the basis for a independant component and is now part of Jakarta Commons.

The Struts framework’s simple validation interface alleviates much of the headache associated with handling data validation, allowing you to focus on validation code and not on the mechanics of capturing data and redisplaying incomplete or invalid data.

In order to do form validation without Validator framework, one has to use validate() method of the form bean (ActionForm class) to perform this task. Also one has to handle error messages during manual validation. Lot of fields that we validate require same logic to validate them, hence code is unneccessarily duplicated (if not managed properly).

Validation framework comes with set of useful routines to handle form validation automatically and it can handle both server side as well as client side form validation. If certain validation is not present, you can create your own validation logic and plug it into validation framework as a re-usable component.

Validator uses two XML configuration files to determine which validation routines should be installed and how they should be applied for a given application, respectively. The first configuration file, validator-rules.xml, declares the validation routines that should be plugged into the framework and provides logical names for each of the validations. The validator-rules.xml file also defines client-side JavaScript code for each validation routine. Validator can be configured to send this JavaScript code to the browser so that validations are performed on the client side as well as on the server side.

The second configuration file, validation.xml, defines which validation routines should be applied to which Form Beans. The definitions in this file use the logical names of Form Beans from the struts-config.xml file along with the logical names of validation routines from the validator-rules.xml file to tie the two together.

Using the Validator framework involves enabling the Validator plug-in, configuring Validator’s two configuration files, and creating Form Beans that extend the Validator’s ActionForm subclasses. The following sections explain in detail how to configure and use Validator.

Create a Struts project

Create a struts web application project. I assume you have working environment set for a Struts project. If not then go through the tutorial: Creating Struts application using Eclipse and create a struts project.

Create Form Beans

struts validator form bean
Create a form bean in your project called CustomerForm and copy following code in it.

package net.viralpatel.struts.validation.form;
import org.apache.struts.validator.ValidatorForm;
public class CustomerForm extends ValidatorForm {
    
    private String name;
    private String telephone;
    private String email;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

We will use this validator plugin to validate this form. Note that the form bean is extended from class ValidatorForm and not ActionForm as we generally do in Struts project.

Add Validator Plug-in in struts-config.xml

In order to use Validator in our project we need to configure it in struts-config.xml file. For this add following code in your struts-config.xml file.

<!-- Validator Configuration -->
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
    <set-property property="pathnames"
        value="/WEB-INF/validator-rules.xml,
                /WEB-INF/validation.xml" />
</plug-in>

This definition tells Struts to load and initialize the Validator plug-in for your application. Upon initialization, the plug-in loads the comma-delimited list of Validator config files specified by the pathnames property. Each config file’s path should be specified by use of a Web application-relative path, as shown in the previous example.

Define validations for the form

validation.xml file struts validator framework

Create a file validation.xml in your applications WEB-INF directory. And copy following content in it.

<?xml version="1.0" encoding="UTF-8" ?>
<!--DOCTYPE form-validation PUBLIC
          "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
          "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
<form-validation>
<global>
    <constant>
    <constant-name>telephoneFormat</constant-name>
    <constant-value>^\d{5,10}$</constant-value>
    </constant>
</global>
<formset>
    <form name="CustomerForm">
        <field property="name" depends="required">
            <arg key="label.name" />
        </field>
        <field property="age" depends="required, integer, intRange">
            <arg0 key="label.age" />
            <arg1 key="${var:min}" resource="false"/>
            <arg2 key="${var:max}" resource="false"/>
            <var>
                <var-name>min</var-name>
                <var-value>1</var-value>
            </var>
            <var>
                <var-name>max</var-name>
                <var-value>125</var-value>
            </var>
        </field>
        <field property="telephone" depends="required, mask">
            <arg key="label.telephone" />
            <arg1 key="label.telephone" />
            <var>
                <var-name>mask</var-name>
                <var-value>${telephoneFormat}</var-value>
            </var>
        </field>
        <field property="email" depends="email">
            <arg0 key="label.email" />
            <arg1 key="label.email" />
        </field>
    </form>
</formset>
</form-validation>

In the above xml file, we have defined the rules for form validation. Note that we are validating form CustomerForm and the fields being validated are name, age, telephone and email. tag defines the validation for a property of form. We can specify different rules like required, integer, email, intRange, mask etc in depends attribute of field tag..

Also you can define constants that can be reused in the validation xml using global constants tag.

Struts-config.xml entry for the action

Following is the entry in struts-config.xml file which maps the Action to our Validator form.

<form-beans>
    <form-bean name="CustomerForm"
        type="net.viralpatel.struts.validation.form.CustomerForm" />
</form-beans>
...
...
...
<action-mappings>
...
    <action path="/customer" name="CustomerForm" validate="true"
        input="/index.jsp"
        type="net.viralpatel.struts.validation.action.CustomerAction">
        <forward name="success" path="/Customer.jsp" />
        <forward name="failure" path="/index.jsp" />
    </action>
...
</action-mappings>

Configuring ApplicationResources.properties

Struts validation framework uses externalization of the error messages. The messages are stored in a property file (ApplicationResource.properties) and are referred by the key values. Copy following in your ApplicationResource.properties (or MessageResource.properties).

label.name= Name
label.email= Email
label.telephone= Telephone
label.age= Age
# general error msgs
errors.header=<font size="2"><UL>
errors.prefix=<LI><span style="color: red">
errors.suffix=</span></LI>
errors.footer=</UL></font>
errors.invalid={0} is invalid.
errors.maxlength={0} can not be greater than {1} characters.
errors.minlength={0} can not be less than {1} characters.
errors.range={0} is not in the range {1} through {2}.
errors.required={0} is required.
errors.byte={0} must be an byte.
errors.date={0} is not a date.
errors.double={0} must be an double.
errors.float={0} must be an float.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.short={0} must be an short.

Create JSP to display the form

Create a JSP file called index.jsp and copy following content in it.

<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<html>
<head>
<title>Struts Validation Framework example.</title>
</head>
<body>
<html:errors />
<html:javascript formName="CustomerForm" />
<html:form action="/customer">
    <bean:message key="label.name" />
    <html:text property="name"></html:text>
    <br />
    <bean:message key="label.age" />
    <html:text property="age"></html:text>
    <br />
    <bean:message key="label.email" />
    <html:text property="email"></html:text>
    <br />
    <bean:message key="label.telephone" />
    <html:text property="telephone"></html:text>
    <br />
    <html:submit value="Submit"></html:submit>
</html:form>
</body>
</html>

Running the application

We are done with our application. Now execute it from any web container (Tomcat in my case) and open in browser.
struts validator form screen

Enter any invalid value in the form and press submit.

struts-validator-form-screen2

Reference :http://viralpatel.net

English: Logo of Русский: Логотип Apache Tomcat

Setting the JAVA_HOME , CATALINA_HOME Environment Variable on Windows

One can do using command prompt
1. set JAVA_HOME=C:\”top level directory of your java install”
2. set CATALINA_HOME=C:\”top level directory of your Tomcat install”
3. set PATH=%PATH%;%JAVA_HOME%\bin;%CATALINA_HOME%\bin

Or you can do the same

  1. Go to system properties.
  2. Go to environment variables and add a new variable with the name  JAVA_HOME and provide variable value as C:\”top level directory of your java install”.
  3. Go to environment variables and add a new variable with the name  CATALINA_HOME and provide variable value as C:\”top level directory of your Tomcat install”.
  4. In path variable add a new variable value as ;%CATALINA_HOME%\bin;

and write startup.bat on command Prompt and press enter tomcat will start up and for shutdown u just write shutdown.bat        once you start the tomcat you can access it like that http://localhost:8080     and access Application Manager using login and password …. if you dont know username and password you can  follow below instructions ….

User and password for Tomcat

By default, Tomcat does not enable admin or manager access. To enable it, you have to edit the “%TOMCAT_FOLDER%/conf/tomcat-users.xml” manually.

File : tomcat-users.xml (before update) , initially, Tomcat comments all users and roles like above.



<!--
  
  <role rolename="role1"/>
  
  
  
-->

File : tomcat-users.xml (after updated)

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
-->
  <role rolename="manager"/>
  <role rolename="admin"/>
  <user username="admin" password="admin" roles="admin,manager"/>
</tomcat-users>

To enable admin access, just update the content like above. Saved it and restart Tomcat, now you can access Tomcat admin or manger pages with user = “admin” and password = “admin“.

International Bibliography of Periodical Liter...

executeQuery()—for getting the data from database
executeUpdate()—for insert,update,delete
execute()—any kind of operations

executeQuery() This is used generally for reading the content of the database. The output will be in the form of ResultSet. Generally SELECT statement is used.

executeUpdate() This is generally used for altering the databases. Generally DROP TABLE or DATABASE, INSERT into TABLE, UPDATE TABLE, DELETE from TABLE statements will be used in this. The output will be in the form of int. This int value denotes the number of rows affected by the query.

execute() If you dont know which method to be used for executing SQL statements, this method can be used. This will return a boolean. TRUE indicates the result is a ResultSet and FALSE indicates it has the int value which denotes number of rows affected by the query.

Deutsch: Logo der Christlich Sozialen Volkspartei

Loading CSV file into Database can be cumbersome task if your Database provider does not offer an out of box feature for this. Most of the time you’ll spend up in creating valid insert statements and putting up values escaping all special characters. Importing CSV files gets a bit complicated when you start doing things like importing files with description fields that can contain punctuation (such as commas or single-double quotation marks).

So here’s a simple Java Utility class that can be used to load CSV file into Database. Note how we used some of the best practices for loading data. The CSV file is parsed line by line and SQL insert query is created. The values in query are binded and query is added to SQL batch. Each batch is executed when a limit is reached (in this case 1000 queries per batch).

Import CSV into Database example

Let’s us check an example. Below is the sample CSV file that I want to upload in database table Customer.

employee.csv – Sample CSV file:

EMPLOYEE_ID,FIRSTNAME,LASTNAME,BIRTHDATE,SALARY
1,Dean,Winchester,27.03.1975,60000
2,John,Winchester,01.05.1960,120000
3,Sam,Winchester,04.01.1980,56000

The Table customer contains few fields. We added fields of different types like VARCHAR, DATE, NUMBER to check our load method works properly.

Table: Customer – Database table

CREATE TABLE Customer (
  EMPLOYEE_ID  NUMBER,
  FIRSTNAME    VARCHAR2(50 BYTE),
  LASTNAME     VARCHAR2(50 BYTE),
  BIRTHDATE    DATE,
  SALARY       NUMBER
)

Following is a sample Java class that will use CSVLoader utility class (we will come to this shortly).

Main.java – Load sample.csv to database

package net.viralpatel.java;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
    private static String JDBC_CONNECTION_URL =
            "jdbc:oracle:thin:SCOTT/TIGER@localhost:1500:MyDB";
    
    public static void main(String[] args) {
        try {
            CSVLoader loader = new CSVLoader(getCon());
            
            loader.loadCSV("C:\\employee.sql", "CUSTOMER", true);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static Connection getCon() {
        Connection connection = null;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            connection = DriverManager.getConnection(JDBC_CONNECTION_URL);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
}

In above Main class, we created an object of class CSVLoader using parameterized constructor and passed java.sql.Connection object.

Then we called the loadCSV method with three arguments. First the path of CSV file, second the table name where data needs to be loaded and third boolean parameter which decides whether table has to be truncated before inserting new records.

Execute this Java class and you’ll see the records getting inserted in table.

csv-load-java-database-example

The CSV is successfully loaded in database.

Let’s check the Utility class now. I strongly recommend you to go through below tutorials as the Utility class combines the idea from these tutorials.

  1. Batch Insert In Java – JDBC
  2. Read / Write CSV file in Java
  3. Check if String is valid Date in Java

The utility class uses OpenCSV library to load and parse CSV file. Then it uses the idea of Batching in JDBC to batch insert queries and execute them. Each CSV value is checked if it is valid date before inserting.

CSVLoader.java – Utility class to load CSV into Database

package net.viralpatel.java;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import au.com.bytecode.opencsv.CSVReader;
/**
 *
 * @author viralpatel.net
 *
 */
public class CSVLoader {
    private static final
        String SQL_INSERT = "INSERT INTO ${table}(${keys}) VALUES(${values})";
    private static final String TABLE_REGEX = "\\$\\{table\\}";
    private static final String KEYS_REGEX = "\\$\\{keys\\}";
    private static final String VALUES_REGEX = "\\$\\{values\\}";
    private Connection connection;
    private char seprator;
    /**
     * Public constructor to build CSVLoader object with
     * Connection details. The connection is closed on success
     * or failure.
     * @param connection
     */
    public CSVLoader(Connection connection) {
        this.connection = connection;
        //Set default separator
        this.seprator = ',';
    }
    
    /**
     * Parse CSV file using OpenCSV library and load in
     * given database table.
     * @param csvFile Input CSV file
     * @param tableName Database table name to import data
     * @param truncateBeforeLoad Truncate the table before inserting
     *          new records.
     * @throws Exception
     */
    public void loadCSV(String csvFile, String tableName,
            boolean truncateBeforeLoad) throws Exception {
        CSVReader csvReader = null;
        if(null == this.connection) {
            throw new Exception("Not a valid connection.");
        }
        try {
            
            csvReader = new CSVReader(new FileReader(csvFile), this.seprator);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("Error occured while executing file. "
                    + e.getMessage());
        }
        String[] headerRow = csvReader.readNext();
        if (null == headerRow) {
            throw new FileNotFoundException(
                    "No columns defined in given CSV file." +
                    "Please check the CSV file format.");
        }
        String questionmarks = StringUtils.repeat("?,", headerRow.length);
        questionmarks = (String) questionmarks.subSequence(0, questionmarks
                .length() - 1);
        String query = SQL_INSERT.replaceFirst(TABLE_REGEX, tableName);
        query = query
                .replaceFirst(KEYS_REGEX, StringUtils.join(headerRow, ","));
        query = query.replaceFirst(VALUES_REGEX, questionmarks);
        System.out.println("Query: " + query);
        String[] nextLine;
        Connection con = null;
        PreparedStatement ps = null;
        try {
            con = this.connection;
            con.setAutoCommit(false);
            ps = con.prepareStatement(query);
            if(truncateBeforeLoad) {
                //delete data from table before loading csv
                con.createStatement().execute("DELETE FROM " + tableName);
            }
            final int batchSize = 1000;
            int count = 0;
            Date date = null;
            while ((nextLine = csvReader.readNext()) != null) {
                if (null != nextLine) {
                    int index = 1;
                    for (String string : nextLine) {
                        date = DateUtil.convertToDate(string);
                        if (null != date) {
                            ps.setDate(index++, new java.sql.Date(date
                                    .getTime()));
                        } else {
                            ps.setString(index++, string);
                        }
                    }
                    ps.addBatch();
                }
                if (++count % batchSize == 0) {
                    ps.executeBatch();
                }
            }
            ps.executeBatch(); // insert remaining records
            con.commit();
        } catch (Exception e) {
            con.rollback();
            e.printStackTrace();
            throw new Exception(
                    "Error occured while loading data from file to database."
                            + e.getMessage());
        } finally {
            if (null != ps)
                ps.close();
            if (null != con)
                con.close();
            csvReader.close();
        }
    }
    public char getSeprator() {
        return seprator;
    }
    public void setSeprator(char seprator) {
        this.seprator = seprator;
    }
}

The class looks complicated but it is simple :)

The loadCSV methods combines the idea from above three tutorials and create insert queries.

Following is the usage of this class if you want to use it in your project:

Usage

CSVLoader loader = new CSVLoader(connection);
loader.loadCSV("C:\\employee.csv", "TABLE_NAME", true);

Load file with semicolon as delimeter:

CSVLoader loader = new CSVLoader(connection);
loader.setSeparator(';');
loader.loadCSV("C:\\employee.csv", "TABLE_NAME", true);

Load file without truncating the table:

CSVLoader loader = new CSVLoader(connection);
loader.loadCSV("C:\\employee.csv", "TABLE_NAME", false);

Hope this helps.

Download Source Code

Load_CSV_Database_Java_example.zip (2.05 MB)

Die Rotationsbefehle. Der Ausgangszustand ist ...

Programming is an art.

There are plenty of compilers around to program.The famous C,the beautiful Java,the useful HTML,the elusive oracle and the simple .net…

So why assembly language????

Those of you who ever had a go at cracking and all other stuff will have a readymade answer to it.No cracking without a crack at assembly language.

If u are not in the cracking Biz why do you need it?

No programmer is complete without mastery over assembly language..your program ruins slow or there is some deep glitch.you work on it day and night and still the glitch remains a glitch.here comes the assembly language.You analyse the processes and come at a diagnosis…

Assembly language makes you powerful.it is the base on which everything is built.

Without assembly language you will always remain a novice.whatever you build or achieve.

So lets start the learning process.

You must have heard that the—-

Assembly language is hard to learn and understand

Its difficult to debug

It’s a messy outfit

Why do you want to save a little space using assembly language when you have so much space?

Believe Me, learning assembly language is easier than most high level languages..

Once you learn assembly language everything else comes naturally..

Assembly language has several benefits:

• Speed. Assembly language programs are generally the fastest programs around.

• Space. Assembly language programs are often the smallest.

• Capability. You can do things in assembly which are difficult or impossible in HLLs.

• Knowledge. Your knowledge of assembly language will help you write better programs,

even when using HLLs.

LESSON1 – THE REGISTERS AND SEGMENTS

 

LESSON 2 – BASIC OPERATORS

 

LESSON3 – INTERRUPTS LABELS AND DB

 

LESSON4 – STACK (PUSH,POP) AND MORE COMMANDS

 

LESSON5 – FLAGS AND JUMPS

 

LESSON6 – MEMORY MOVING

 

LESSON7 – PROCEDURES AND MACROS

 

LESSON8 – EXTERNALS AND PUBLICS

 

LESSON9 – INCLUDING INFO IN THE EXE

 

LESSON10 – PORTS, TIPS, SUMMARY