read text file content and insert it into a mysql database - java

Good day . I've the following code which i'm trying to make work . I have to read the content of a text file , which contains questions and save it to the database testsystem .
The main problem that i'm facing is that it's not inserted in the database. and i'm not sure whether it is reading the textfile or not.
any help will be glady appreciated
JFrame and main
public class StudentTestSystems {
public static void main(String[] args) {
try {
Lecturer panel = new Lecturer();
panel.setVisible(true);
panel.setLocationRelativeTo(null);
panel.setResizable(false);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Lecturer class
public class Lecturer extends JFrame implements ActionListener {
Font font = null;
private JTextField fileField;
private JButton uploadBtn;
private JLabel message;
private JPanel panel;
public Lecturer() {
super("LECTURE MENU");
this.setSize(500, 270);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
font = new Font("Times New Roman", Font.BOLD, 14);
panel = new JPanel();
panel.setLayout(null);
panel.setOpaque(true);
fileField = new JTextField();
fileField.setFont(font);
fileField.setBounds(130, 110, 200, 25);
Font font2 = new Font("Times New Roman", Font.BOLD + Font.ITALIC, 12);
message = new JLabel("Type in the file name with it's extension. eg: File.txt");
message.setFont(font2);
message.setBounds(130, 140, 280, 25);
message.setOpaque(true);
uploadBtn = new JButton("UPLOAD");
uploadBtn.setFont(font);
uploadBtn.setBounds(340, 110, 95, 21);
panel.add(fileField);
panel.add(uploadBtn);
panel.add(message);
add(panel);
/////// register event
uploadBtn.addActionListener(this);
exit.addActionListener(this);
}
public void actionPerformed(ActionEvent ev) {
String file = fileField.getText();
SetGetQuestionFileName setGet = new SetGetQuestionFileName(file);
FileInputStream fis = null;
PreparedStatement preparedStmt = null;
try {
String myUrl = "jdbc:mysql://localhost:3306/testsystem";
Connection conn = DriverManager.getConnection(myUrl, "root", "cput");
if (ev.getActionCommand().equals("UPLOAD")) {
File filePathString = new File(file);
fis = new FileInputStream(filePathString);
if (fileField.getText().length() == 0) {
JOptionPane.showMessageDialog(null, "File field can't be empty. Try again", "ERROR", JOptionPane.INFORMATION_MESSAGE);
} else {
if (filePathString.exists() && filePathString.isFile()) {
try {
// the mysql insert statement
String query = " insert into users (category_questions, questions, quest_opt_a, , quest_opt_b, , quest_opt_c, quest_opt_d, correct_option_answer )"
+ " values (?, ?, ?, ?, ?)";
// create the mysql insert preparedstatement
preparedStmt = conn.prepareStatement(query);
preparedStmt.setString(1, "JDBC");
preparedStmt.setString(2, fileField.getText());
preparedStmt.setAsciiStream(3, fis, (int) filePathString.length());
//preparedStmt.setString (3, "a");
preparedStmt.setString(4, "b");
preparedStmt.setString(5, "c");
preparedStmt.setString(6, "d");
preparedStmt.setString(7, "a");
preparedStmt.executeUpdate();
// execute the preparedstatement
preparedStmt.executeUpdate();
// myfile.closing();
conn.close();
JOptionPane.showMessageDialog(null, "File successfuly uploaded", "INFORMATION", JOptionPane.INFORMATION_MESSAGE);
fileField.setText("");
} catch (Exception ex) {
} finally {
preparedStmt.close();
fis.close();
conn.close();
}
} else {
JOptionPane.showMessageDialog(null, "File coudn't be found. Do check file name.", "ERROR", JOptionPane.INFORMATION_MESSAGE);
}
}
}
} catch (Exception ex) {
}
if (ev.getActionCommand().equals("LOGOUT")) {
System.exit(0);
}
}
}
SetQuestionFileName class
public class SetGetQuestionFileName {
String myfile;
public SetGetQuestionFileName(String file) {
setFileName(file);
}
public void setFileName(String file) {
myfile = file;
}
public String getFileName() {
return myfile;
}
}

Here a short version on how you can read a file (line by line):
Scanner scanner = new Scanner(filename);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
}
This is your query. There where too many , or empty column names and the number of columns and ? does not match:
String query = " insert into users (
category_questions,
questions,
quest_opt_a,
, // empty column name
quest_opt_b,
, // empty column name
quest_opt_c,
quest_opt_d,
correct_option_answer
)" + " values (?, ?, ?, ?, ?)"; // you have 7 columns (without the empty ones) but only 5 ?
Here a reformatted version of your query. I just removed the , and added 2 ?
String query = "INSERT INTO users (
category_questions,
questions,
quest_opt_a,
quest_opt_b,
quest_opt_c,
quest_opt_d,
correct_option_answer
) VALUES (?, ?, ?, ?, ?, ?, ?)";
Now I am trying to understand the values you want to add:
preparedStmt.setString(1, "JDBC"); // so JDBC is your category ?
preparedStmt.setString(2, fileField.getText()); // I guess this should be the question?
preparedStmt.setString(3, "a"); // according to the column names this needs to be option A
preparedStmt.setString(4, "b"); // option b
preparedStmt.setString(5, "c"); // option c
preparedStmt.setString(6, "d"); // option d
preparedStmt.setString(7, "a"); // answer
So far so good. If I interpreted the column names correctly, this should work. The only thing left is now to get the real question text for column 2 (from the file).
I don't know how your file looks like, so I can just give you an example:
textfile in this format: question? answerA, answerB, answerC, answerD, correctAnswer
-------------------------------------------------------------------------------------
What is the color of the sun? pink, blue, yellow, green, c
What is the smallest number? 3, 1, 7, 200, b
And this would be how you could read the file and fill the database all at once:
// prepare the query
String query = "INSERT INTO users (
category_questions,
questions,
quest_opt_a,
quest_opt_b,
quest_opt_c,
quest_opt_d,
correct_option_answer
) VALUES (?, ?, ?, ?, ?, ?, ?)";
// load the file
Scanner scanner = new Scanner(filename);
// read the file line by line
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] questionAnswer = line.split("?")[ // line.split["?"] will split the line into two strings, right at the ? and put those two strings into an array.
String question = questionAnswer[0] // so [0] will access the first element in that array - the question
String[] answers = questionAnswer[1].split(","); // now we split the string after the ? into many strings divided by comma
preparedStmt.setString(1, "JDBC");
preparedStmt.setString(2, question);
preparedStmt.setString(3, answers[0]);
preparedStmt.setString(4, answers[1]);
preparedStmt.setString(5, answers[2]);
preparedStmt.setString(6, answers[3]);
preparedStmt.setString(7, answers[4]);
preparedStmt.executeUpdate();
}
There are many ways to read the line from your text file and split it into question and answer. It depends on the file you read from and how it is formatted.
FIY: you execute preparedStmt.executeUpdate(); twice at the end :)

Related

Change password code error with Java & MySQL

I'm building this component where I can change the password that is stored in my MySQL database using Java Eclipse. I have this typical system where you have to enter your old password and new password and have that old password checked to match the one in the system.
public class ChangePassword implements ActionListener {
public void actionPerformed(ActionEvent event) {
JPasswordField oldPswrd = new JPasswordField(50);
JPasswordField newPswrd = new JPasswordField(50);
JLabel j = new JLabel("Type in old password: ");
JLabel j2 = new JLabel("Type in new password: ");
j.setFont(new Font("Times New Roman", Font.PLAIN, 15));
j2.setFont(new Font("Times New Roman", Font.PLAIN, 15));
Object[] message = {
j, oldPswrd,
j2, newPswrd,
};
int result = JOptionPane.showConfirmDialog(null, message,
"CHANGE PASSWORD", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
char[] oldp = oldPswrd.getPassword();
String oldP = String.valueOf(oldp);
char[] p = newPswrd.getPassword();
String newP = String.valueOf(p);
System.out.println("New name: " + newP);
//// PROBLEM SEEMS TO START HERE ///////////////////////////////////////////
try {
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println("connection success!!");
String sql = "SELECT * FROM user_info WHERE user_id = ? && user_password = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, user_id);
statement.setString(2, password);
ResultSet rs = statement.executeQuery();
if (rs.next()){
String oldPassword = rs.getString("user_password");
if (oldP.equals(oldPassword)) {
String sql1 = "UPDATE user_info SET user_password = ? WHERE user_id = ?";
PreparedStatement statement1 = connection.prepareStatement(sql1);
statement1.setString(1, newP);
statement1.setString(2, user_id);
int rows2 = statement1.executeUpdate();
if (rows2 > 0) {
System.out.println("UPDATE PASSWORD!");
}
}
} else {
JLabel l = new JLabel("Old password does not match");
l.setFont(new Font("Times New Roman", Font.PLAIN, 15));
l.setHorizontalAlignment(SwingConstants.CENTER);
JOptionPane.showMessageDialog(null, l, "ERROR", JOptionPane.PLAIN_MESSAGE);
}
} catch (SQLException e) {
System.out.println("& i oop");
e.printStackTrace();
}
///////// PROBLEM SEEMS TO END HERE ///////////////////////////////////////////
frame.setVisible(false);
new UserMain(user_id, name, newP);
}
}
}
I have this table with a row of data already set in as a test. However, whenever I try to change the password - typing in the correct old password and typing in another new one - it always shows
old password does not match
There's no syntax or connection errors so I figured the problem is a logic error or something I couldn't catch. Also, the java portions work fine, I've checked those already. The problem seems to be between the try and catch parts of my code.
password is your database password, not one of the user passwords. Change
statement.setString(2, password);
to
statement.setString(2, oldP);
Where are you taking this "username" and "password" from?
Also you are passing the same "password" variable to find the user that is using for the DB connection. I think it should be change to "oldP ".

Insert parse CSV file to SQL Server

I'm parsing CSV file using OpenCSV library. I managed to skip first desired lines, choose only wanted columns and print it to console.
Now I'm struggling with inserting this to MSSQL database.
That's my code for parsing file:
JFileChooser fileopen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter(
"CSV file", "csv");
fileopen.setFileFilter(filter);
int ret = fileopen.showDialog(null, "Choose file");
if (ret == JFileChooser.APPROVE_OPTION) {
CsvParserSettings settings = new CsvParserSettings();
settings.detectFormatAutomatically();
settings.setHeaderExtractionEnabled(true);
settings.selectIndexes(7, 8, 13, 14);
settings.setNumberOfRowsToSkip(9);
List<String[]> rows = new CsvParser(settings).parseAll((fileopen.getSelectedFile()), "UTF-8");
rows.forEach(arr -> System.out.println(Arrays.toString(arr)));
Now code
INSERT INTO dbo.Glass(Nr_Temp) values(Arrays.toString(rows.get(1)));
Is getting me whole row instead column (which is understandable:)) but is there any other solution to return columns values to insert them to SQL database?
UPDATED
You need to iterate over String[] to get access to each separate value for a column.
PreparedStatement ps = connection.prepareStatement("INSERT INTO dbo.Szyby_temp(nr_zlec_klienta, nr_ref_klienta, szerokosc, wysokosc, ilosc, opis_dodatkowy, data_importu) VALUES(?, ?, ?, ?, ?, ?, getdate())");
int maxBatchSize = 100; //Using batching for performance
int currentBatchSize = 0;
for (String[] row : rows) {
int i = 1;
for (String columnValue : row) {
ps.setString(i++, columnValue); //Parameter indexes start with 1
}
ps.addBatch();
if (++currentBatchSize % maxbatchSize == 0) {
ps.executeUpdate();
}
}
ps.executeUpdate(); //if number of rows in csv file is not divisible by maxbatchSize
Thanks Ivan, I removed optimalization as files are small (less then 100 rows each) and also changed
ps.executeupdate() to `ps.executeBatch()
as it was uploading only last row, now It's working perfect, thank you for your time.
Here is my changed code
try {
PreparedStatement ps = conn.prepareStatement("INSERT INTO dbo.Szyby_temp(nr_zlec_klienta, nr_ref_klienta, szerokosc, wysokosc, ilosc, opis_dodatkowy, data_importu) VALUES(?, ?, ?, ?, ?, ?, getdate())");
for (String[] row : rows) {
int i = 0;
for (String columnValue : row) {
ps.setString(++i, columnValue); //Parameter indexes start with 1
}
ps.addBatch();
}
ps.executeBatch(); //if number of rows in csv file is not divisible by maxbatchSize
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e, "ERROR", JOptionPane.ERROR_MESSAGE);
}

SQLite syntax error with JTable

Hi want to to create a JTable with SQLite Database. The data should come from a SQLite database and are stored in this . Now new details to be added by typing in a text field . However, I get the error message : "java.sql.SQLException: near "(": syntax error"
What´s wrong?
public class SQLite {
public static DefaultTableModel model = new DefaultTableModel();
private static JTextField fieldID;
private static JTextField fieldName;
private static JTextField fieldAge;
private static JTextField fieldAddress;
private static JTextField fieldSalary;
public static void main( String args[] ) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
c.commit();
JFrame f = new JFrame();
f.setLayout(new GridLayout(5,1));
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
fieldID = new JTextField("ID");
fieldName = new JTextField("Name");
fieldAge = new JTextField("Age");
fieldAddress = new JTextField("Address");
fieldSalary = new JTextField("Salary");
String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " +
"VALUES (fieldID.getText(), feldName.getText(), Age.getText(), feldAddress.getText(), feldSalary.getText()";
stmt.executeUpdate(sql);
JTable table = new JTable(model);
f.add( new JScrollPane( table ) );
model.addColumn("id");
model.addColumn("name");
model.addColumn("age");
model.addColumn("address");
model.addColumn("salary");
ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" );
while ( rs.next() ) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
float salary = rs.getFloat("salary");
model.addRow(new Object[] {id, name, age, address, salary});
}
/**JTextField feldID = new JTextField("ID");
JTextField feldName = new JTextField("Name");
JTextField feldAge = new JTextField("Age");
JTextField feldAddress = new JTextField("Address");
JTextField feldSalary = new JTextField("Salary");
**/
f.pack();
f.setVisible( true );
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
}
Here is your problem :
"VALUES (fieldID.getText(), feldName.getText(), Age.getText(), feldAddress.getText(), feldSalary.getText()";
They're read as litterals and not as a reference to a getter.
Here is what you'll have to replace it with by using concatenation.
"VALUES ("+fieldID.getText()+","+feldName.getText()+","+Age.getText()+","+feldAddress.getText()+","+feldSalary.getText()+");";
Use a PreparedStatement. It is easier to code and maintain and will manage the delimiters for you:
String sql = "INSERT INTO COMPANY (ID, NAME, AGE, ADDRESS, SALARY) VALUES (?, ?, ?, ?, ?)";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, fieldID.getText() );
stmt.setString( 2, fieldname.getText() );
stmt.setString( 3, ... );
stmt.setString( 4, ... );
stmt.setString( 5, ... );
stmt.executeUpdate();
but now i get the java sql Exception: "no such column: ID"
Well, the message is self explanatory. There is no "ID" column. We can't help you with that because only you know the proper names of the columns since you are the one that created the database.

java sqlite autocommit slow

Background: I'm working with Java in Netbeans.
I'm reading rows from a CSV file and inserting them into a SQLite database. Very basic stuff I would think. From examples found at this site and elsewhere I've constructed the following code. It works but I'm surprised to see how slow it is. It takes 3.95 seconds to load 46 lines into the db! Using the Netbeans Profiler I can see it's the autoCommit() that's taking the bulk of the time, 3.7 seconds.
What am I doing wrong? Or, is this just the penalty for using SQLite instead of MySQL?
public static void LoadJCNAClassesTable(Connection aConn, String strPath) throws SQLException{
String [] nextLine;
String strDivision;
String strClass;
String strNotes;
String strDescription;
Statement stat = aConn.createStatement();
stat.executeUpdate("drop table if exists JCNAClasses;");
String q = "create table JCNAClasses ('ID' INTEGER PRIMARY KEY AUTOINCREMENT, 'division' TEXT NOT NULL, 'class' TEXT NOT NULL UNIQUE, 'description' TEXT NOT NULL, 'note' TEXT NOT NULL, 'node' INTEGER NOT NULL);";
stat.executeUpdate(q);
CSVReader reader;
int iLine;
String JCNAClassesCSV = strPath + "\\JCNAClassesCsv.txt" ;
try {
reader = new CSVReader(new FileReader(JCNAClassesCSV ));
iLine = 0;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
// System.out.println(nextLine[0] + nextLine[1] );
if (iLine > 0){
strDivision = nextLine[0];
strClass = nextLine[1];
strDescription= nextLine[2];
strNotes= nextLine[3];
PreparedStatement prep = aConn.prepareStatement( "insert into JCNAClasses ('division', 'class', 'description', 'note', 'node') values ( ?, ?, ?, ?, ?);");
prep.setString(1, strDivision); // note that the comma seems not to be a problem
prep.setString(2,strClass);
prep.setString(3,strDescription);
prep.setString(4,strNotes);
prep.setInt(5,iLine);
prep.addBatch();
aConn.setAutoCommit(false);
prep.executeBatch();
aConn.setAutoCommit(true);
}
iLine++;
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Entries.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(Entries.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(LoadSQLiteConcoursDatabase.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void LoadConcoursEntriesTable(Connection aConn, String strPath) throws SQLException{
String [] nextLine;
String strEntryName;
String strClass;
Integer intYear;
String strDescription;
String strOwnerFirst;
String strOwnerLast;
Integer intJCNA;
String strColor;
String strPlate;
Integer intNode;
Long intPersonnel_id;
Long intJaguar_id;
ResultSet generatedKeys;
String strStatus;
int intPersonnelNode;
ResultSet r;
CSVReader reader;
String q;
int iLine;
PreparedStatement prep;
ResultSet rs;
Statement stat = aConn.createStatement();
//
// Concourse Personnel Table: Owners, Judges, & Interested parties
//
stat.executeUpdate("drop table if exists ConcoursPersonnel");
// status: Owner = "O"; "J" = Judge; "OJ" = Owner & Judge; "IP" = Interested party, e.g., spouse, restorer
q = "create table ConcoursPersonnel ('personnel_id' INTEGER PRIMARY KEY AUTOINCREMENT , 'ownerfirst' TEXT NOT NULL, 'ownerlast' TEXT NOT NULL, 'jcna' INTEGER NOT NULL UNIQUE ON CONFLICT IGNORE, 'status' TEXT NOT NULL, 'node' INTEGER NOT NULL UNIQUE)";
stat.executeUpdate(q);
//
// Concours Jaguar Table
//
stat.executeUpdate("drop table if exists ConcoursJaguars");
q = "create table ConcoursJaguars ('jaguar_id' INTEGER PRIMARY KEY AUTOINCREMENT , 'class' TEXT NOT NULL, 'year' TEXT NOT NULL, 'description' TEXT NOT NULL, 'Color' TEXT, 'plate' TEXT, 'node' INTEGER NOT NULL UNIQUE)";
stat.executeUpdate(q);
//
// Entry Table ( a Relationship or "link" between Personnel & Jaguars
//
stat.executeUpdate("drop table if exists ConcoursEntries");
q = "create table ConcoursEntries (entry_name TEXT NOT NULL, personnel_id INTEGER NOT NULL, jaguar_id INTEGER NOT NULL, UNIQUE (personnel_id, jaguar_id), FOREIGN KEY (personnel_id) REFERENCES ConcoursPersonnel (Personnel_ID), FOREIGN KEY (jaguar_id) REFERENCES ConcoursPersonnel (jaguar_id))";
stat.executeUpdate(q);
String EntriesCSV = strPath + "\\EntriesCsv.txt" ;
strStatus = "O"; // not in the CSV data so set to Owner
try {
reader = new CSVReader(new FileReader(EntriesCSV ));
iLine = 0;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
// System.out.println(nextLine[0] + nextLine[1] );
if (iLine > 0){
strEntryName = nextLine[0];
strClass = nextLine[1];
intYear= Integer.parseInt(nextLine[2]);
strDescription= nextLine[3];
strOwnerFirst= nextLine[4];
strOwnerLast= nextLine[5];
intJCNA = Integer.parseInt(nextLine[6]) ;
strColor= nextLine[7];
strPlate= nextLine[8];
intNode= Integer.parseInt(nextLine[9]); // Since Jaguars are 1-to-1 with Entries this is used as Node number for both. However, it can't be used for Personnel Node
//
// Load Owners into Personnel Table
//
Statement s = aConn.createStatement();
r = s.executeQuery("SELECT COUNT(*) AS rowcount FROM ConcoursPersonnel");
r.next();
intPersonnelNode = r.getInt("rowcount") +1 ; // Assignes Personnel node numbers as a continuous sequence
prep = aConn.prepareStatement( "insert into ConcoursPersonnel ('ownerfirst', 'ownerlast', 'jcna', 'status', 'node' ) values ( ?, ?, ?, ?, ?);");
//prep.setString(1, strEntryName); // note that the comma seems not to be a problem
prep.setString(1,strOwnerFirst);
prep.setString(2,strOwnerLast);
prep.setInt(3,intJCNA);
prep.setString(4,strStatus);
prep.setInt(5,intPersonnelNode);
prep.addBatch();
aConn.setAutoCommit(false); // starts transaction
prep.executeBatch();
aConn.setAutoCommit(true); // ends transaction
aConn.setAutoCommit(false); // starts transaction
stat = aConn.createStatement();
generatedKeys = stat.executeQuery("SELECT last_insert_rowid()");
intPersonnel_id = 0L; // won't be used
if (generatedKeys.next()) {
intPersonnel_id = generatedKeys.getLong(1);
}
else{
System.out.println("No Personnel ID found in LoadConcoursEntriesTable");
System.exit(-1);
}
aConn.setAutoCommit(true); // Commits transaction.
//
// Load Entry cars into the ConcoursJaguars table
//
prep = aConn.prepareStatement( "insert into ConcoursJaguars ('class', 'year', 'description', 'color', 'plate', 'node' ) values ( ?, ?, ?, ?, ?, ?);");
prep.setString(1,strClass);
prep.setInt(2,intYear);
prep.setString(3,strDescription);
prep.setString(4,strColor);
prep.setString(5,strPlate);
prep.setInt(6,intNode); //
prep.addBatch();
aConn.setAutoCommit(false);
prep.executeBatch();
aConn.setAutoCommit(true);
q = "select jaguar_id from ConcoursJaguars where node == " + intNode + ";";
rs = stat.executeQuery(q);
intJaguar_id = rs.getLong("jaguar_id");
prep = aConn.prepareStatement( "insert into ConcoursEntries (entry_name, personnel_id, jaguar_id) values ( ?, ?, ?);");
//prep.setString(1, strEntryName); // note that the comma seems not to be a problem
prep.setString(1,strEntryName);
prep.setLong(2,intPersonnel_id);
prep.setLong(3,intJaguar_id);
prep.addBatch();
aConn.setAutoCommit(false);
prep.executeBatch();
aConn.setAutoCommit(true);
}
iLine++;
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Entries.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(Entries.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(LoadSQLiteConcoursDatabase.class.getName()).log(Level.SEVERE, null, ex);
}
}
Setting autoCommit to true is actually executes commit within the loop. Thus, there is no batch operation running: you commit every time you iterate through the loop. To have a batch operation you need to:
add aConn.setAutoCommit(false); before your while operator
remove lines wrapping prep.executeBatch(); (i.e., aConn.setAutoCommit(false); and aConn.setAutoCommit(true);)
move prep.executeBatch(); out of your loop
add line with aConn.commit(); right after your while loop
aConn.setAutoCommit(false);
PreparedStatement prep = aConn.prepareStatement( "insert into JCNAClasses ('division', 'class', 'description', 'note', 'node') values ( ?, ?, ?, ?, ?);");
while ((nextLine = reader.readNext()) != null) {
if (iLine > 0){
// some preparations go here
prep.addBatch();
}
iLine++;
}
prep.executeBatch();
aConn.commit();
You are recreating your PreparedStatement everytime you go through your loop. This should be moved to just before the while loop.
Also the setAutoCommit option should be set once outside the loop, and then you commit your statements when you hit a reasonable ceiling or when you are done.
You can see an example posted here: Java: Insert multiple rows into MySQL with PreparedStatement

batch insert takes only one query and fails to take all the query in java

i have a method which has to insert into two tables, i have used batch insert for that.
my problem is it takes the second query and inserts in to that table and fails to insert into first table that is fails to take first query.
this is what is my code :
public String saveVillageDetails(VillagesViewModel viewmodel, String functionType) {
int[] saveOrupdateStatus = null;
StringBuffer disctrictQuery = new StringBuffer();
String saveOrupdateStatusMessage = "";
Connection connection = getConnection();
PreparedStatement districtPS = null;
ResultSet rs = null;
if (connection != null) {
try {
connection.setAutoCommit(false);
if(functionType.equals("add")){
// to insert in villages table
disctrictQuery.append(" INSERT INTO m_villages(districtid,village,creation_date,last_created_by) ");
disctrictQuery.append(" VALUES (?, ?, ?,?) ");
districtPS = connection.prepareStatement(disctrictQuery.toString());
districtPS.setInt(1, viewmodel.getDistrictid());
districtPS.setString(2, viewmodel.getVillage());
districtPS.setTimestamp(3, getCurrentDate());
districtPS.setInt(4,viewmodel.getUserid());
districtPS.addBatch();
// to insert in regions table
disctrictQuery=new StringBuffer();
disctrictQuery.append(" INSERT INTO m_regions(villageid,creation_date,last_created_by) ");
disctrictQuery.append(" VALUES (?, ?, ?) ");
districtPS = connection.prepareStatement(disctrictQuery.toString());
districtPS.setInt(1, getLatestVilalgeID());
districtPS.setTimestamp(2, getCurrentDate());
districtPS.setInt(3,viewmodel.getUserid());
districtPS.addBatch();
}else if(functionType.equals("edit")){
// to update villages table
disctrictQuery.append("UPDATE m_villages SET districtid=? ,village=? ,updation_date=? ,last_updated_by=? ");
disctrictQuery.append(" WHERE villageid=? ");
districtPS = connection.prepareStatement(disctrictQuery.toString());
districtPS.setInt(1, viewmodel.getDistrictid());
districtPS.setString(2, viewmodel.getVillage());
districtPS.setTimestamp(3, getCurrentDate());
districtPS.setInt(4,viewmodel.getUserid());
districtPS.setInt(5,viewmodel.getVillageid());
districtPS.addBatch();
disctrictQuery=new StringBuffer();
// to update regiions table
disctrictQuery.append("UPDATE m_regions SET villageid=?,updation_date=? ,last_updated_by=? ");
disctrictQuery.append(" WHERE regionid=? ");
districtPS = connection.prepareStatement(disctrictQuery.toString());
districtPS.setInt(1, viewmodel.getVillageid());
districtPS.setTimestamp(2, getCurrentDate());
districtPS.setInt(3,viewmodel.getUserid());
districtPS.setInt(4,getRegionID(viewmodel.getVillageid()));
districtPS.addBatch();
}
saveOrupdateStatus = districtPS.executeBatch();
if (saveOrupdateStatus.length > 0) {
if(functionType.equals("add")){
saveOrupdateStatusMessage = "Village Details Added successfully";
}else if(functionType.equals("edit")){
saveOrupdateStatusMessage = "Village Details Modified successfully";
}
connection.commit();
connection.setAutoCommit(true);
} else {
if(functionType.equals("add")){
saveOrupdateStatusMessage = "Failed to Add Village Details";
}else if(functionType.equals("edit")){
saveOrupdateStatusMessage = "Failded to Modify Village Details";
}
}
} catch (Exception ex) {
ex.printStackTrace();
//use log to print the exception ex.printStackTrace();
} finally {
try {
closeConnection(connection, rs, districtPS);
} catch (Exception ex) {
ex.printStackTrace();
//use logger here
}
}
}
return saveOrupdateStatusMessage;
}
when i printed the statement i get like this :
com.mysql.jdbc.ServerPreparedStatement[2] - INSERT INTO m_regions(villageid,creation_date,last_created_by) VALUES (18, '2012-11-06 17:41:25', 1)
and the first query is missing in the batch.
what could be the problem.
Please help
Regards
Please refactor your code in the way as below:
if(functionType.equals("add")){
// to insert in villages table
districtPS = connection.prepareStatement("INSERT INTO m_villages(districtid,village,creation_date,last_created_by) VALUES (?, ?, ?,?) ",
Statement.RETURN_GENERATED_KEYS);
districtPS.setInt(1, viewmodel.getDistrictid());
districtPS.setString(2, viewmodel.getVillage());
districtPS.setTimestamp(3, getCurrentDate());
districtPS.setInt(4,viewmodel.getUserid());
districtPS.executeUpdate();
ResultSet keySet = districtPS.getGeneratedKeys();
int villageId = 0;
if (keySet.next()) {
villageId = keySet.getInt(1);
}
// to insert in regions table
districtPS = connection.prepareStatement(" INSERT INTO m_regions(villageid,creation_date,last_created_by) VALUES (?, ?, ?) ",
Statement.RETURN_GENERATED_KEYS);
districtPS.setInt(1, villageId);
districtPS.setTimestamp(2, getCurrentDate());
districtPS.setInt(3,viewmodel.getUserid());
districtPS.executeUpdate();
}

Categories