How to import a .xls file to mysql Database using java? - java

I'm trying to upload an Excel file .xls to my MySQL Database using Java NetBeans but I didn't find any solution.
I tried with CSV file and it worked fine, but I would still like to use the .xls file format.
To achieve this I want the user to click a JButton in my JFrame, choose an Excel file by using JFileChooser and then save that file in my database.
Following is the image of what I currently have:
And this is the code I used so far:
private void importer_csv_btnActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename = f.getAbsolutePath();
import_interne_txt.setText(filename);
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
while ((line = br.readLine()) != null) {
String[] value = line.split(",");
String sql = "INSERT INTO Interne(Matricule,Nom,Prénom,Sexe,Date_naissance,Nationalité,Lieu_naissance,Willaya,Email,Moyenne1,Moyenne2,Redoublement,Conseil,Num_Phone,Password,CPI_Code) " + "VALUES('" + value[0] + "','" + value[1] + "','" + value[2] + "','" + value[3] + "','" + value[4] + "','" + value[5] + "','" + value[6] + "','" + value[7] + "','" + value[8] + "','" + value[9] + "','" + value[10] + "','" + value[11] + "','" + value[12] + "','" + value[13] + "','" + value[14] + "','" + value[15] + "')";
pst = Con.prepareStatement(sql);
pst.executeUpdate();
}
br.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
Update_table();
}

Use Apache POI to read data from xls files.
Example:
public extractDataFromXls(String fileName, sheetName) throws FileNotFoundException {
FileInputStream fileInputStream = new FileInputStream(fileName);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet worksheet = workbook.getSheet(sheetName);
HSSFRow row = worksheet.getRow(0);
for (short i = 0; i < 5; i++) {
HSSFCell cell = row.getCell(i);
String value = cell.getStringCellValue();
System.out.println(value);
}
}

Related

how to simulate Excel control codes in String

One web project I'm involved in requires generating a CSV to the user.
One field is notes and there can be multiple notes in the field, separated by a return (alt-enter in Excel), appearing as
A USER entered on 02/17/2023: Test note
A USER entered on 02/17/2023: This is another note
Is it possible to insert control codes into a Java string that Excel will pick up and format the cell properly?
For what it's worth, this was my attempt:
}else if (formType.equalsIgnoreCase("downloadCSV")) {
Date d = new Date();
String filename = "C:/temp/rtTmp" + d.getTime() + ".csv";
File f = new File(filename);
List<Contact> contactList = RetentionTrackDatabaseUtil.getContacts();
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write("name,"
+ "gender,"
+ "age,"
+ "DOB,"
+ "DOH,"
+ "DOR,"
+ "DOS,"
+ "dateContact,"
+ "reason,"
+ "status,"
+ "empNum,"
+ "shift,"
+ "phone,note(s)\n");
for (Contact c : contactList) {
System.out.println(c.getAge());
bw.append("\"" + c.getName() + "\"" + ","
+ c.getGender() + ","
+ Integer.toString(c.getAge()) + ","
+ (c.getDOB()!=null?RetentionTrackUtil.sdf.format(c.getDOB()):"") + ","
+ (c.getDOH()!=null?RetentionTrackUtil.sdf.format(c.getDOH()):"") + ","
+ (c.getDOR()!=null?RetentionTrackUtil.sdf.format(c.getDOR()):"") + ","
+ (c.getDOS()!=null?RetentionTrackUtil.sdf.format(c.getDOS()):"") + ","
+ (c.getDateContact()!=null?RetentionTrackUtil.sdf.format(c.getDateContact()):"") + ","
+ c.getReason() + ","
+ c.getStatus() + ","
+ c.getEmpNum() + ","
+ c.getShift() + ","
+ c.getPhone() + ",");
for(Note n: c.getNoteList()){
bw.append("(" + n.getEnteredBy() + " on " + RetentionTrackUtil.sdf.format(n.getNoteDate()) + ")" + n.getNote() + "\\n");
}
bw.append("\n");
}
bw.close();
sendFile(response, filename);
}

Query Creation Does Not Print All Indexes

When I create the file and write in the query, does it write only once? why?
for (spinelliIndex = 0; spinelliIndex < spinelli.getVeicoli_id().size(); spinelliIndex++) {
boolean match = false;
for (veicoloIndex = 0; veicoloIndex < veicoloDb.getVeicoloId().size(); veicoloIndex++) {
if (spinelli.getVeicoli_targa().get(spinelliIndex).equals(veicoloDb.getTarga().get(veicoloIndex))) {
match = true;
// Stampa a Video
System.out.println(spinelli.getVeicoli_targa().get(spinelliIndex) + " = "
+ veicoloDb.getTarga().get(veicoloIndex) + " --> "
+ spinelli.getVeicoli_id().get(spinelliIndex) + " --> "
+ veicoloDb.getVeicoloId().get(veicoloIndex));
// Scrivi nella riga i
row = sheet.getRow(spinelliIndex);
// Scrivi nella colonna AC indice 28
cell = row.createCell(28);
// Scrivi il ciclo in tutte le righe nella colonna AC indice 28
sheet.getRow(spinelliIndex).createCell(28)
.setCellValue(spinelli.getVeicoli_id().get(spinelliIndex));
FileOutputStream fos = new FileOutputStream(filePath);
// Scrivi nel file EXCEL
wb.write(fos);
fos.close();
// Scrivi NEl file .txt
// Crea la Query e scrivi nel file
file = new File(path);
fw = new FileWriter(file);
fw.write("UPDATE veicolo SET ID = " + "'" + spinelli.getVeicolo_newid().get(spinelliIndex) + "'" + ","
+ "CREATE_DATE = " + "'" + veicoloDb.getCreate_date().get(veicoloIndex) + "'" + ","
+ "MODIFIED_DATE = " + "'" + veicoloDb.getModified_date().get(veicoloIndex) + "'" + "," + "UUID = "
+ "'" + veicoloDb.getUuid().get(veicoloIndex) + "'" + "," + "CLASSE_EURO = " + "'"
+ veicoloDb.getClasse_euro().get(veicoloIndex) + "'" + "," + "CODICE_CLIENTE_ORIGINARIO = " + "'"
+ veicoloDb.getCodice_cliente_originario().get(veicoloIndex) + "'" + "," + "CONTRATTO = " + "'"
+ veicoloDb.getContratto().get(veicoloIndex) + "'" + "," + "DATA_FINE_VALIDITA = " + "'"
+ veicoloDb.getData_fine_validita().get(veicoloIndex) + "'" + "," + "DATA_INIZIO_VALIDITA = " + "'"
+ veicoloDb.getData_inizio_validita().get(veicoloIndex) + "'" + "," + "DISPONIBILITA = " + "'"
+ veicoloDb.getDisponibilita().get(veicoloIndex) + "'" + "," + "NAZIONE = " + "'"
+ veicoloDb.getNazione().get(veicoloIndex) + "'" + "," + "TARGA = " + "'" + veicoloDb.getTarga().get(veicoloIndex)
+ "'" + "," + "TIPO_DI_POSSESSO = " + "'" + veicoloDb.getTipo_di_possesso().get(veicoloIndex) + "'"
+ "," + "ID_ANAGRAFICA = " + "'" + veicoloDb.getId_anagrafica().get(veicoloIndex) + "'"
+ "FROM DISPOSITIVO_VEICOLO WHERE dispositivo_veicolo.id_anagrafica = veicolo.id_anagrafica"
+ ";" + "\n");
fw.flush();
fw.close();
}
}
// Targhe non trovate
if (!match) {
System.out.println("Targa non trovata: " + spinelli.getVeicoli_targa().get(spinelliIndex));
}
}
}
I'm not sure what is your expected behavior on your program, but I guess you want to write(append) your file multiple times, right?
In your code, create new file (new File()) and close the writer (fw.close()) in the loop.
It looks, the program overwrite to the same file multiple times.
So, if you want to append(not overwrite), I recommend you to put file creation and file closing on the outside of the loop like the following (dummy code):
file = new File(path);
fw = new FileWriter(file);
for (spinelliIndex = 0; spinelliIndex < spinelli.getVeicoli_id().size(); spinelliIndex++) {
fw.write("something");
}
fw.close();
Also, fw.close() will call fw.flush(). If you don't have any specific reason to write it, you can remove it.

how to solve this "not using PreparedStatement method" problem?

This is query section
#FXML
void dbsave(ActionEvent event) throws SQLException {
String user = parUsertxt.getText();
String first = parFirstNametxt.getText();
String last = parLastNametxt.getText();
String cnic = parCnictxt.getText();
String date = parDatetxt.getValue().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
String address = parAddresstxt.getText();
String status = parStatustxt.getText();
String province = parProvincetxt.getText();
String district = parDistricttxt.getText();
String tehsil = parTehsiltxt.getText();
String area = parAreatxt.getText();
String phone = parPhonetxt.getText();
String ephone = parEmPhonetxt.getText();
String gender = parGendertxt.getSelectionModel().getSelectedItem();
String father = parFatherNametxt.getText();
String fathercnic = parFatherCNICtxt.getText();
// BinaryStreamValueFactory personimage;// how can i use this to store an image
String query = "INSERT INTO `landrecord`.`parowner` (`UserName`, `FirstName`, `LastName`, `CNIC`, `DateOfBirth`, `Address`, `Status`, `Province`, `Tehsil`, `District`, `Area`, `PhoneNo`, `EmergencyPhoneNo`, `Gender`, `FatherName`, `FatherCNIC`,'ImagePerson') " +
"VALUES ('" + user + "','" + first + "','" + last + "','" + cnic + "','" + date + "','" + address + "','" + status + "','" + province + "','" + tehsil + "','" + district + "','" + area + "','" + phone + "','" + ephone + "','" + gender + "','" + father + "','" + fathercnic + "')";
if (connectionClass.execAction(query)) {
System.out.println("Data Successful Save");
savebtn.getScene().getWindow().hide();
try {
Parent root = FXMLLoader.load(getClass().getResource("parLandRecord.fxml"));
Stage stage = new Stage();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
} catch (IOException ex) {
System.out.print(ex.getLocalizedMessage());
}
}else{
System.out.println("Insertion Failed.");
}
}
This is the button to show image in image view
#FXML
void personCnicbtn(ActionEvent event) throws MalformedURLException {
fileChooser1 = new FileChooser();
fileChooser1.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Select Image","*.png","*.jpg","*.gif"));
File file1 = fileChooser1.showOpenDialog(null);
if (file1 != null){
imageFile1 = file1.toURI().toURL().toString();
Image image1 = new Image(imageFile1);
personCnicImage.setImage(image1);
}else{
System.out.println("image Error");
}
}
this is the code I'm working on Now I need to save an image without using preparedStatement Or if there is a way to use preparedStatement then please tell me how?
If you are storing file into database i recommended store in blob format.it is good to handle.here in code i am simple giving info in your code how to store using prepared statement.
Connection connection = null;
PreparedStatement statement = null;
FileInputStream inputStream = null;
File image = new File("your_file_path_which_is_getting_from_FileChooser");
inputStream = new FileInputStream(image);
/**
* establish connection of database.
*/
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/your_db", "your_username", "your_pw");
statement = connection.prepareStatement("insert into parowner(UserName,FirstName,LastName,CNIC,DateOfBirth,Address,Status,Province,Tehsil,District,Area,PhoneNo,EmergencyPhoneNo,Gender,FatherName,FatherCNIC,ImagePerson) " + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
statement.setString(1, "UserName");
/**
* set image as byte stream
*/
statement.setBinaryStream(17, (InputStream) inputStream, (int)(image.length()));
statement.executeUpdate();

sql Command has not properly ended

I'm using sql developer and netbeans when ever i try to insert data into the table this error "sql Command has not properly ended".
This is what i tried.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
dbconnection db = new dbconnection();
try {
db.connect();
db.stm = db.con.createStatement();
int result = db.stm.executeUpdate(
"insert into payment values'" + txt_paymentid.getText() + "','" + txt_reservation.getText() +"',
" + "'"+txt_fname.getText()+"',
'"+txt_lname.getText()+"' ,'"+txt_roomid.getText()+"' ,'"+txt_rate.getText()+"' ," + " '"+((JTextField)txt_datein.getDateEditor().getUiComponent()).getText()+"' ,"
+ "'"
((JTextField
)txt_dateout.getDateEditor().getUiComponent()).getText() + "'," + "'" + txt_days.getText() + "','" + txt_payment.getText() + "','" + txt_balance.getText() + "'"
);
if (result > 0) {
JOptionPane.showMessageDialog(this, "Data has been saved succesfully");
} else {
JOptionPane.showMessageDialog(this, "no data has been saved");
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, e.toString());
}
}
For a start
The sql should be in the ()
executeUpdate()("insert...
->
executeUpdate("insert...)
second it looks like the insert command itself it not valid
insert into table values (' ....

Parsing csv line to Java objects

I was wondering if someone here could help me, I can't find a solution for my problem and I have tried everything.
What I am trying to do is read and parse lines in a csv file into java objects and I have succeeded in doing that but after it reads all the lines it should insert the lines into the database but it only inserts the 1st line the entire time and I don't no why. When I do a print it shows that it is reading all the lines and placing them in the objects but as soon as I do the insert it wants to insert only the 1st line.
Please see my code below:
public boolean lineReader(File file){
BufferedReader br = null;
String line= "";
String splitBy = ",";
storeList = new ArrayList<StoreFile>();
try {
br = new BufferedReader(new FileReader(file));
while((line = br.readLine())!=null){
line = line.replace('|', ',');
//split on pipe ( | )
String[] array = line.split(splitBy, 14);
//Add values from csv to store object
//Add values from csv to storeF objects
StoreFile StoreF = new StoreFile();
if (array[0].equals("H") || array[0].equals("T")) {
return false;
} else {
StoreF.setRetailID(array[1].replaceAll("/", ""));
StoreF.setChain(array[2].replaceAll("/",""));
StoreF.setStoreID(array[3].replaceAll("/", ""));
StoreF.setStoreName(array[4].replaceAll("/", ""));
StoreF.setAddress1(array[5].replaceAll("/", ""));
StoreF.setAddress2(array[6].replaceAll("/", ""));
StoreF.setAddress3(array[7].replaceAll("/", ""));
StoreF.setProvince(array[8].replaceAll("/", ""));
StoreF.setAddress4(array[9].replaceAll("/", ""));
StoreF.setCountry(array[10].replaceAll("/", ""));
StoreF.setCurrency(array[11].replaceAll("/", ""));
StoreF.setAddress5(array[12].replaceAll("/", ""));
StoreF.setTelNo(array[13].replaceAll("/", ""));
//Add stores to list
storeList.add(StoreF);
}
} //print list stores in file
printStoreList(storeList);
executeStoredPro(storeList);
} catch (Exception ex) {
nmtbatchservice.NMTBatchService2.LOG.error("An exception accoured: " + ex.getMessage(), ex);
//copy to error folder
//email
}
return false;
}
public void printStoreList(List<StoreFile> storeListToPrint) {
for(int i = 0; i <storeListToPrint.size();i++){
System.out.println( storeListToPrint.get(i).getRetailID()
+ storeListToPrint.get(i).getChain()
+ storeListToPrint.get(i).getStoreID()
+ storeListToPrint.get(i).getStoreName()
+ storeListToPrint.get(i).getAddress1()
+ storeListToPrint.get(i).getAddress2()
+ storeListToPrint.get(i).getAddress3()
+ storeListToPrint.get(i).getProvince()
+ storeListToPrint.get(i).getAddress4()
+ storeListToPrint.get(i).getCountry()
+ storeListToPrint.get(i).getCurrency()
+ storeListToPrint.get(i).getAddress5()
+ storeListToPrint.get(i).getTelNo());
}
}
public void unzip(String source, String destination) {
try {
ZipFile zipFile = new ZipFile(source);
zipFile.extractAll(destination);
deleteStoreFile(source);
} catch (ZipException ex) {
nmtbatchservice.NMTBatchService2.LOG.error("Error unzipping file : " + ex.getMessage(), ex);
}
}
public void deleteStoreFile(String directory) {
try {
File file = new File(directory);
file.delete();
} catch (Exception ex) {
nmtbatchservice.NMTBatchService2.LOG.error("An exception accoured when trying to delete file " + directory + " : " + ex.getMessage(), ex);
}
}
public void executeStoredPro(List<StoreFile> storeListToInsert) {
Connection con = null;
CallableStatement st = null;
try {
String connectionURL = MSSQLConnectionURL;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
con = DriverManager.getConnection(connectionURL, MSSQLUsername, MSSQLPassword);
for(int i = 0; i <storeListToInsert.size();i++){
st = con.prepareCall( "IF EXISTS (SELECT * FROM tblPay#RetailStores WHERE StoreID = " + storeListToInsert.get(i).getStoreID() + " AND RetailID = "+ storeListToInsert.get(i).getRetailID() + ")"
+ " UPDATE tblPay#RetailStores "
+ " SET RetailID = '" + storeListToInsert.get(i).getRetailID() + "',"
+ " StoreID = '" + storeListToInsert.get(i).getStoreID() + "',"
+ " StoreName = '" + storeListToInsert.get(i).getStoreName() + "',"
+ " TestStore = 0,"
+ " Address1 = '" + storeListToInsert.get(i).getAddress1() + "',"
+ " Address2 = '" + storeListToInsert.get(i).getAddress2() + "',"
+ " Address3 = '" + storeListToInsert.get(i).getAddress3() + "',"
+ " Address4 = '" + storeListToInsert.get(i).getAddress4() + "',"
+ " Address5 = '" + storeListToInsert.get(i).getAddress5() + "',"
+ " Province = '" + storeListToInsert.get(i).getProvince() + "',"
+ " TelNo = '" + storeListToInsert.get(i).getTelNo() + "',"
+ " Enabled = 1"
+ " ELSE "
+ " INSERT INTO tblPay#RetailStores ( [RetailID], [StoreID], [StoreName], [TestStore], [Address1], [Address2], [Address3], [Address4], [Address5], [Province], [TelNo] , [Enabled] ) "
+ " VALUES "
+ "('" + storeListToInsert.get(i).getRetailID() + "',"
+ "'" + storeListToInsert.get(i).getStoreID() + "',"
+ "'" + storeListToInsert.get(i).getStoreName() + "',"
+ "0,"
+ "'" + storeListToInsert.get(i).getAddress1() + "',"
+ "'" + storeListToInsert.get(i).getAddress2() + "',"
+ "'" + storeListToInsert.get(i).getAddress3() + "',"
+ "'" + storeListToInsert.get(i).getAddress4() + "',"
+ "'" + storeListToInsert.get(i).getAddress5() + "',"
+ "'" + storeListToInsert.get(i).getProvince() + "',"
+ "'" + storeListToInsert.get(i).getTelNo() + "',"
+ "1)");
st.executeUpdate();
}
con.close();
} catch (Exception ex) {
nmtbatchservice.NMTBatchService2.LOG.error("Error executing Stored proc with error : " + ex.getMessage(), ex);
nmtbatchservice.NMTBatchService2.mailingQueue.addToQueue(new Mail("support#nmt-it.co.za", "Service Email Error", "An error occurred during Store Import failed with error : " + ex.getMessage()));
}
}
Any advise would be appreciated.
Thanks
Formatting aside, your code is wrong (I truncated the part of the query):
for(int i = 0; i <storeListToInsert.size();i++){
st = con.prepareCall( "IF EXISTS (SELECT * FROM tblPay#RetailStores ...
+ "'" + storeListToInsert.get(i).getTelNo() + "',"
+ "1)");
st.executeUpdate();
}
Don't do a classical for loop while foreach exists and can be better to use, and even if you do a classical for loop, use local variables, eg:
for(int i = 0; i <storeListToInsert.size();i++){
StoreFile item = storeListToInsert.get(i);
st = con.prepareCall( "IF EXISTS (SELECT * FROM tblPay#RetailStores ...
+ "'" + item.getTelNo() + "',"
+ "1)");
st.executeUpdate();
}
Which could translate as:
for (StoreFile item : storeListToInsert) {
st = con.prepareCall( "IF EXISTS (SELECT * FROM tblPay#RetailStores ...
+ "'" + item.getTelNo() + "',"
+ "1)");
st.executeUpdate();
}
Now, the second problem is your PreparedStatement. A PreparedStatement allow reusing, which means you don't need to create PreparedStatement per item which is what you are doing.
Also, you need to close the statement otherwise, you will exhaust resources..
You must not create it in the for loop, but before, like this:
PreparedStatement st = null;
try {
st = con.prepareCall( "IF EXISTS (SELECT * FROM tblPay#RetailStores ...
+ "SET RetailID = :RetailID ,"
+ "1)");
for (StoreFile item : storeListToInsert) {
st.setString(":RetailID", item.getRetailID());
st.executeUpdate();
}
} finally {
if (null != st) {st.close();}
}
In brief:
You need to close the PreparedStatement after usage, because it is a memory leak otherwise.
You need to rewrite your query using either named parameters, either positional parameter (like: ? or ?1 for first parameter, and so on). I favor named parameters, but they are not always available. The example I linked all use positional parameters.
You need to set the value for each parameters in the for loop, and care about the type. I expected here that getRetailID() is a String, but it might be a Long in that case that would be st.setLong.
Your query is reusable, avoiding the need to reparse it/resend it to the SQL Server. You just send the parameter's values. Beside, you can also batch update.
A PreparedStatement for a statement that you generate (like you are doing) is overkill, and beside, it is missing SQL escapement to protect the String you inject to your query to avoid it being badly interpreted (aka SQL errors) or worst, to do what it was not intended for (like, even if it is far fetched, dropping the whole database, etc).
The executeUpdate() return the number of updated rows. You can check it to see if there was updates.
You can also use Batch statement, which can help performances.
And finally, you can use opencsv to parse common CSV files.

Categories

Resources