java sqlite autocommit slow - java

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

Related

DB2 SQL Error: SQLCODE=-117, SQLSTATE=42802, SQLERRMC=null, DRIVER=3.68.61

I'm experiencing this problem while developing in Java and inserting records into a DB2 database.
sqlInsert = "INSERT into SI_Orders (SellersNo,OrderDate,ShipDatePlanned,"
+ "Warehouse,OrderType,ShipToName,ShipToAddress1,"
+ "ShipToCity,ShipToProvState,ShipToPostalZip,ShipToCountry" + ") "
+ "VALUES (?, ?, ?,'01','DO','bob','a','toronto','ON','h0h0h0','CA')";
try {
con = dc.getConnection();
con.setAutoCommit(false);
db2Stmt = con.prepareStatement(sqlInsert);
for (Order order : orderWrapper.orders) {
save1 = con.setSavepoint();
db2Stmt.setString(1, order.getOrderId());
db2Stmt.setTimestamp(2, shipStnDateFormat( order.getOrderDate() ) );
db2Stmt.setString(3, null); // PONo
/*
* db2Stmt.setTimestamp(4, shipStnDateFormat(order.getShipByDate()));
*/
db2Stmt.executeUpdate();
//con.commit();
} // end of enhanced for each block
} // end of try block
catch (SQLException e1) {
e1.printStackTrace();
if (con != null) {
try {
System.err.print("Transaction is being rolled back.");
con.rollback();
}
catch (SQLException se) {
se.printStackTrace();
}
} // end of if(con != null) block
} // end of catch block
finally {
// Clean-up code
con.setAutoCommit(true);
if (db2Stmt != null) {
db2Stmt.close();
}
if (con !=null){
con.close();
}
} // end of finally block
} // end of insertDB method
private Timestamp shipStnDateFormat(String shipByDate) {
SimpleDateFormat shipStnDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat standardDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String parsedFinalFormattedDate = null;
Date finalDate = null;
if (shipByDate == null)
return new java.sql.Timestamp(0); // return a dummy value
else {
try {
Date parsedShipByDate = shipStnDateFormat.parse(shipByDate); //
parsedFinalFormattedDate = standardDateFormat.format(parsedShipByDate); //
finalDate = standardDateFormat.parse(parsedFinalFormattedDate); //
} catch (ParseException e) {
e.printStackTrace();
}
return new java.sql.Timestamp(finalDate.getTime());
} // end of else statement
} // end of shipStnDateFormat method`
I get this error...
DB2 SQL Error: SQLCODE=-117, SQLSTATE=42802, SQLERRMC=null, DRIVER=3.6in8.61
Obviously, I'd like it to insert all three columns without throwing a SQL Exception.
Also, here's the DDL I used to create the table which shows the datatypes of each column and whether a NOT NULL constraint is enforced or not.
The first column "OrderId" is an identity column, so I haven't issued an insert parameter for that.
CREATE TABLE SI_Orders (
OrderId INTEGER NOT NULL generated always as identity (start with 0,
increment by 1, no cache),
SellersNo VARCHAR(20) NOT NULL,
OrderDate Timestamp(0) NOT NULL,
PONo VARCHAR(20),
ShipDatePlanned Timestamp(0) NOT NULL,
CONSTRAINT PK_SI_Orders PRIMARY KEY (OrderId)
);
You are setting:
db2Stmt.setString(3, null); // PONo
While your model states for that column:
ShipDatePlanned Timestamp(0) NOT NULL,
So setting it to NULL is not allowed, update parameter 3 to a not NULL value should solve this issue.
To add columns to a query you would do this:
sqlInsert = "INSERT into SI_Orders (SellersNo,OrderDate,ShipDatePlanned,PONo,"
+ "Warehouse,OrderType,ShipToName,ShipToAddress1,"
+ "ShipToCity,ShipToProvState,ShipToPostalZip,ShipToCountry" + ") "
+ "VALUES (?, ?, ?,?,'01','DO','bob','a','toronto','ON','h0h0h0',?)";
So adding a column at a random location in the string, and adding a ? in the VALUES would add the column.
The index of the ? starts with 1 and matches only up the the column name which the parameter is replaced with.
For example: In this sample ShipToCountry would be index 5

Update a single value inside a table with java using MySQL

Currently I have this code:
PreparedStatement prepCust = connection.prepareStatement("insert into Customer values (?, ?, ?, ?, ?, ?);");
ResultSet results = connection.createStatement()
.executeQuery("SELECT phonenumber FROM customer WHERE phonenumber = " + cust.getPhoneNumber());
results.next();
try {
if (results.getString(1).equals(cust.getPhoneNumber())) {
System.out.println("User already exist in database, adding one to order count");
results = connection.createStatement().executeQuery(
"SELECT numberoforders FROM customer WHERE phonenumber = " + cust.getPhoneNumber());
results.next();
int updated = results.getInt(1) + 1;
System.out.println(updated);
results = connection.createStatement()
.executeQuery("SELECT * FROM customer WHERE phonenumber = " + cust.getPhoneNumber());
results.next();
prepCust.setString(1, results.getString(1));
prepCust.setString(2, results.getString(2));
prepCust.setString(3, results.getString(3));
prepCust.setString(4, results.getString(4));
prepCust.setInt(5, updated);
prepCust.setInt(6, results.getInt(6));
prepCust.executeUpdate();
}
} catch (SQLException sql) {
sql.printStackTrace();
prepCust.setString(1, cust.getfName());
prepCust.setString(2, cust.getlName());
prepCust.setString(3, cust.getAddress());
prepCust.setString(4, cust.getPhoneNumber());
prepCust.setInt(5, 1);
prepCust.setInt(6, 0);
prepCust.executeUpdate();
}
And the table it is accessing is:
create table customer(
firstname varchar(50) NOT NULL,
lastname varchar(50) NOT NULL,
streetaddress varchar(150) NOT NULL,
phonenumber varchar(10) NOT NULL,
numberoforders int(11) default 1;
customer_id int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY(customer_id,phonenumber)
UNIQUE KEY customer_id (customer_id)
);
My issue is, when I tried to just update a single value using prepCust.setInt(5, someInt);, and then attempt to execute the update, I would get an exception saying that I never input anything for prepCust.setString(1,whatever); and so on. My thoughts for surrounding the code with a trycatch was if the code throws an exception, then that must mean that field does not exist inside the table, and to create a new field that contains all the entered data. If the code doesn't throw an exception, that means that the phone number does exist inside the table, and to find what row that phonenumber is on, and add one to the amount of orders that customer has. My issue now with this code is that it will add an entire new column of information to the table, even if it has the same phonenumber and customer id, throw an exception telling me that, and then I'm stuck with values of the exact same where the value doesn't increment that I need to. How can I just update a single value in a column? Is there anyway to do that with a prepared statement?
The problem is because you are using an INSERT statement when you are looking to do an UPDATE statement. Since the entry already exists, you want to update that one value that exists with the same phone number. When it doesn't exist you put your prepCust insert statement in your catch block to make the new entry.
String phonenumber = cust.getPhoneNumber();
Statement s = connection.createStatement();
ResultSet results = s.executeQuery("SELECT phonenumber, numberoforders FROM customer WHERE phonenumber = " + phonenumber);
results.next();
try {
if (results.getString(1).equals(phonenumber)) {
System.out.println("User already exist in database, adding one to order count");
int updated = results.getInt(2) + 1;
System.out.println(updated);
PreparedStatement updateCust = connection.prepareStatement("UPDATE customer SET numberoforders = ? WHERE phonenumber = ?");
updateCust.setInt(1, updated);
updateCust.setString(2, phonenumber);
updateCust.executeUpdate();
}
} catch (SQLException sql) {
sql.printStackTrace();
try {
PreparedStatement prepCust = connection.prepareStatement("insert into Customer values (?, ?, ?, ?, ?, ?);");
prepCust.setString(1, cust.getfName());
prepCust.setString(2, cust.getlName());
prepCust.setString(3, cust.getAddress());
prepCust.setString(4, cust.getPhoneNumber());
prepCust.setInt(5, 1);
prepCust.setInt(6, 0);
prepCust.executeUpdate();
} catch (SQLException sql2) {
sql2.printStackTrace();
}
}

mysql, java - Get last inserted auto increment id from one table and insert it again on another table

its duplicate question with Get last inserted auto increment id in mysql
I'm creating a group it insert on M_GROUPS.
M_GROUPS table:
GROUP_ID INT AUTO_INCREMENT,
GROUP_CREATOR_ID INT
which from session.
I need to take GROUP_ID and GROUP_CREATOR_ID and insert it on
M_GROUP_MEMBERS table as
GROUP_ID INT,
MEMBER_ID INT.
My problem is I can't take auto increment value GROUP_ID from M_GROUPS
public void groupCreation(String groupname, int grouptype, int creator_id) {
DatabaseService oDatabaseService = new DatabaseService();
Connection connection = oDatabaseService.connect();
try {
Statement stmt = null;
stmt = connection.createStatement();
String sql;
sql = "INSERT INTO M_GROUPS( GROUP_NAME, GROUP_CREATOR_ID,
GROUP_TYPE, CREATION_TIME)"
+ " VALUES ('"
+ groupname
+ "','"
+ creator_id
+ "','"
+ grouptype + "',NOW())";
//stmt.executeUpdate(sql);
stmt.executeUpdate(sql);
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (connection != null)
connection.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
Use getGeneratedKeys() method from your Statement object to identify the new auto generated values. Iterate the returned ResultSet object to get the newly generated key values in the order of batch statements.
Change:
stmt.executeUpdate(sql);
To:
int rowsAffected =
stmt.executeUpdate( sql, Statement.RETURN_GENERATED_KEYS );
ResultSet rs = stmt.getGeneratedKeys();
//******************************************************
// in case of batch insert, you can check how many are inserted
rs.last();
int rows = rs.getRow();
System.out.println( "Generated keys count: " + rows );
//******************************************************/
int currentRow = 1;
rs.beforeFirst();
while( rs.next() ) {
System.out.println( /**/( currentRow++ ) + " = " + /**/rs.getInt( 1 ) );
} // while rs
Once you have this auto generated key value in a variable, you can use it with other SQL statements, to store in other tables.
Note: Call to getGeneratedKeys() may throw java.sql.SQLFeatureNotSupportedException, if the JDBC driver, that you are using, does not support this method.

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();
}

How to insert reference values in database using JDBC?

I am trying to insert values into Oracle 10g database using the code below but its giving an error of "Missing Expression" on execution. I have to pass reference values into the insert clause but do not know the exact syntax or way of doing it.
Please help me through this.
Thanks.
Student Table:-
Sid VARCHAR2(200) PRIMARY KEY CHECK(Sid>0),
Pass_word VARCHAR2(10) NOT NULL,
S_name VARCHAR2(20) NOT NULL,
G_name VARCHAR2(20) ,
Branch VARCHAR2(10) NOT NULL,
D_company VARCHAR2(20) ,
B_Percent INT NOT NULL CHECK(B_Percent<100),
twelth_percent INT NOT NULL CHECK(twelth_percent<100),
tenth_percent INT NOT NULL CHECK(tenth_percent<100),
Certify VARCHAR2(30),
Semester INT NOT NULL CHECK(Semester<9),
D_Birth DATE NOT NULL,
Sex VARCHAR2(6) NOT NULL
CODE:
Connection connection = null;
try
{
// Load the JDBC driver
String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driverName);
connection = DriverManager.getConnection("jdbc:odbc:placement","siddharth","sid");
studentID = StudentID.getText();
spassword = PasswordField.getPassword();
studentname = NameField.getText();
Gname = GuardianField.getText();
branch = BranchField.getText();
dcompany = DcompanyField.getText();
bpercent = BtechField1.getText();
twelthpercent = TwelthField.getText();
tenthpercent = TenthField.getText();
semester = SemesterField.getText();
certify = CertificationField.getText();
sex = SexCombo.getActionCommand();
date = (Date) DateTextField1.getValue();
Statement stmt = connection.createStatement();
stmt.executeUpdate("insert into student " +"(sid,pass_word,s_name,g_name,branch,d_company,b_percent,twelth_percent,tenth_percent,certify,semester,d_birth,sex)"+
"values(studentID, spassword,studentname,Gname,branch,dcompany,bpercent,twelthpercent,tenthpercent,certify,semester,date,sex)" );
stmt.close();
connection.close();
}
catch (ClassNotFoundException e) {
// Could not find the database driver
JOptionPane.showMessageDialog(null,e);
}
catch (SQLException e) {
// Could not connect to the database
JOptionPane.showMessageDialog(null,e);
}
Currently your SQL statement looks like:
insert into student (sid, pass_word, ...) values (studentID, spassword, ...)
The variable names mean nothing to the SQL itself.
You should use a prepared statement. For example, your SQL should look like this:
insert into student (sid, pass_word, ...) values (?, ?, ...)
and then you use:
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, studentID);
stmt.setString(2, spassword);
// etc
See the JDBC tutorial on prepared statements for more information.
To be on the safe side you should use prepared statements.
Prepare the Query String
String updateString = "update " + dbName + ".COFFEES " +
"set SALES = ? where COF_NAME = ?";
Create a PrepartedStatement with this query:
updateSales = connnection.prepareStatement(updateString);
Fill the ? spaceholders with you values:
updateSales.setInt(1, myVariable1);
updateSales.setString(2, myVariable2);
execute the Query
updateSales.executeUpdate();

Categories