so i have to build an application where i have to read values from a csv file(excel)and insert them in mySQL.i can do the reading part however I'm fairly stumped by how do i insert the values to the database.
Any help regarding this matter is apprecaited.

Recommended Answers

All 5 Replies

@thines01 thanks for the help but what I wanted to know was a method to insert CSV into the database,,if you can help me with this I would greatly apprecaite it..
thanks,.

Are you asking how to split the CSV into separate variables that are fed to SQL and sent to the database?

yes precisely thats what I'm asking.

Well, that can be quite extensive depending on the schema of your database and the number of column.
The correct way would be to create a prepared statement with SQL parameters that you fill on each loop.
The simple (less-efficient) way would be to create a new SQL string each loop and issue that to the database.
Here is an example of building a new string on each loop if given a CSV file containing three values:

import   java.util.*;
import   java.io.*;

public class SplitPrep
{
   public static void main(String[] args)
   {
      try
      {
         String strFilename = "C:\\science\\java\\DaniWeb\\419950\\CsvFile.csv";
         String strData = "";

         BufferedReader fileIn = new BufferedReader(new FileReader(strFilename));
         fileIn.readLine();

         String strSqlFmt = "INSERT INTO MYTABLE (MY_THIS, MY_THAT, MY_OTHER) VALUES('%s', '%s', '%s')";

         while(null != (strData = fileIn.readLine()))
         {
            System.out.println(strData);
            String[] arr = strData.split(",");

            System.out.printf(strSqlFmt, arr[0], arr[1], arr[2]);
         }

         fileIn.close();
      }
      catch(Exception exc)
      {
         System.out.println(exc.getMessage());
         return;
      }
   }
}

You would need to add code to open the database and use the built SQL to issue commands to the database.
Some of this will change depending on the database you're using.

Connecting to a database
Insert Example

There are plenty of other examples on the web.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.