inserting multiple data iteratively into a table in java database (derby) gives error - derby

I've written a program that takes care of registration and each time i try to insert multiple new users at a time with different id it gives the error message:
java.sql.SQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL130217122630580' defined on 'STCEPARTICIPANTS'.
here is the action passed from a button WHICH instructs the data to be saved:
private void printsavebtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String query1= "insert into STCEPARTICIPANTS values("
+speno1tf.getText()+",'"+sname1tf.getText()+"','"
+fname1tf.getText()+"','"+uni1cb.getSelectedItem()
+"')";
String query2= "insert into STCEPARTICIPANTS values("
+speno1tf.getText()+",'"+sname1tf.getText()+"','"
+fname1tf.getText()+"','"+uni1cb.getSelectedItem()
+"')";
String query3= "insert into STCEPARTICIPANTS values("
+speno1tf.getText()+",'"+sname1tf.getText()+"','"
+fname1tf.getText()+"','"+uni1cb.getSelectedItem()
+"')";
String query4= "insert into STCEPARTICIPANTS values("
+speno1tf.getText()+",'"+sname1tf.getText()+"','"
+fname1tf.getText()+"','"+uni1cb.getSelectedItem()
+"')";
String [] queryarray= {query1,query2,query3,query4};
int speno1,speno2,speno3,speno4;
String task;
if(fname1tf.getText().equals("")||sname1tf.getText().equals("")||speno1tf.getText().equals("")
||uni1cb.getSelectedItem().equals("-")|| fname2tf.getText().equals("")||sname2tf.getText().equals("")||speno2tf.getText().equals("")
||uni2cb.getSelectedItem().equals("-") || fname3tf.getText().equals("")||sname3tf.getText().equals("")||speno3tf.getText().equals("")
||uni3cb.getSelectedItem().equals("-") || fname4tf.getText().equals("")||sname4tf.getText().equals("")||speno4tf.getText().equals("")
||uni4cb.getSelectedItem().equals("-") ){
JOptionPane.showMessageDialog(rootPane, "Please enter the fields marked '*'");
}
else {
try{
speno1=Integer.parseInt(speno1tf.getText());
speno2=Integer.parseInt(speno2tf.getText());
speno3=Integer.parseInt(speno3tf.getText());
speno4=Integer.parseInt(speno4tf.getText());
int [] taskit = {speno1,speno2,speno3,speno4};
for(int count2=0;count2<taskit.length;count2++){
task= "select * from STCEPARTICIPANTS where spe_number="+taskit[count2];
DBOptions.executeNonQuery(queryarray[count2]);
if(SearchData.searchSpeno(task)==true){
JOptionPane.showMessageDialog(rootPane, "Sorry, this member is already in the database./t Please go to Profile to renew of view membership details. Thank you!");
}
}
the class SearchData is given below:
public static boolean searchSpeno(String task){
String query =task;
ResultSet rs = DBOptions.executeSQLQuery(query);
if(rs!=null)
{
try
{
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
if(colCount > 0)
{
try
{
if(rs.next() && ! rs.getString("spe_number").equals(""))
{
return true;
}
else
{
return false;
}
}
catch(SQLException e)
{
JOptionPane.showMessageDialog(null, e,"Search Error", 3);
return false;
}
}
else
{
//JOptionPane.showMessageDialog(null, "Invalid Employee ID","Search Error", 3);
return false;
}
}
catch(SQLException ex)
{
//JOptionPane.showMessageDialog(null, ex.getMessage(),"Error Occured", 2);
return false;
}
}
else
{
return false;
}
}
}
}
the class DBOptions is :
public static boolean executeNonQuery(String sqlString)
{
try
{
Statement stmt = con.createStatement();
stmt.executeUpdate(sqlString);
JOptionPane.showMessageDialog(null,"success!");
return true;
//return the number of rows affected
}
catch(SQLException e)
{
//display error message
JOptionPane.showMessageDialog(null, e.getMessage()+"\nPlease Try Again","Non Query Execution Failure", 1);
e.printStackTrace();
return false;
}
}
public static ResultSet executeSQLQuery(String sqlQuery)
{
try
{
Statement stmt = con.createStatement();
return stmt.executeQuery(sqlQuery); //query successfully executed
}
catch(SQLException e)
{
//display error message
JOptionPane.showMessageDialog(null, e.getMessage()+"\nPlease Try Again","Query Execution Failure", 1);
return null; //sql query execution failed
}
}
}
Please, i have seen some problems like this and i have tried the different forms of solution but no head way. I need to get this ready for a mini project defense. I appreciate your response. Thank you.

How did you create the table? Can you paste the CREATE TABLE statement into your question?
Each row in your table must have a unique value for each column which is defined either as PRIMARY KEY or as UNIQUE, and Derby is enforcing that constraint.
Go back to your table definition, figure out for which columns you have specified either PRIMARY KEY or UNIQUE on the column, and then look at your program to figure out what values you are providing for those columns.
Then modify your program so that it provides a unique value for each such column.

Related

calling my apex method in apex trigger getting the error

public static void insertInboundJive(Map<Id, String> mapCases){
try{
system.debug('Aditya');
Map<Id, String> mapCases1 = new Map<Id, String>();
Map<Id, Integer> mapIncrements = new Map<Id, Integer>();
//List<ICS_Case_Interaction__c> lstCaseInteraction;
if(mapCases != null && mapCases.size() > 0) {
List<ICS_Case_Interaction__c> lstCaseInteraction = [ SELECT Id,case__r.origin FROM ICS_Case_Interaction__c Where case__r.Id =:mapCases.keySet()];
for(ICS_Case_Interaction__c caseInteracts :lstCaseInteraction ){
if(caseInteracts.case__r.Id != null && caseInteracts.case__r.Status == 'New Customer Message'){
system.debug('**AdityaDebug**' +caseInteracts.case__r.Id);
system.debug('**AdityaDebug**' +caseInteracts.case__r.Status);
mapcases1.put(caseInteracts.case__r.Id , TYPE_JIVE_INBOUND);
Integer intIncrement = mapIncrements.get(caseInteracts.case__r.Id);
system.debug('Increment' +intIncrement);
if(intIncrement != null){
intIncrement++;
system.debug('Increment++' +intIncrement);
}
else {
intIncrement = 1;
}
mapIncrements.put(caseInteracts.case__r.Id, intIncrement);
}
}
if(mapCases.size() > 0) {
insertByCaseAsync(mapCases, mapIncrements);
}
}
}
catch(Exception ex){
Core_Log_Entry.logEntryWithException('Case Interaction Metrics', 'CaseInteraction','insertInboundEmail', 'Error', null, null, ex);
}
}
This is my Method in the class.I am trying to call the apex method in the trigger.but its throwing the error.Could you please help me and try to reach out the best.
The error which I am getting was
line 188, col 106. Method does not exist or incorrect signature: void insertInboundJive(List) from the type ICS_Case_Interactions_Trigger_Handler
if(trigger.isUpdate) {
if(Label.ICS_Case_Interaction_Metrics.equals('1')) {ICS_Case_Interactions_Trigger_Handler.insertInboundJive(trigger.new);}
}
You are trying to pass the wrong parameters. In the method you have defined that when called you need to pass a Map where the values are String however you are passing Trigger.new which is a list of Objects. My approach is to handle the mapping in the trigger and then manipulate data in the controller:
In this case you can do the below to pass the records and get the string of data you want in the controller.. or do it in the trigger so you don't change the controller.
Map<Id,Contact> map = new Map<Id,ICS_Case_Interaction__c>(); // new map
for(ICS_Case_Interaction__c con :trigger.new){
map.put(con.Id, con); // enter the records you need for the method
}
if(trigger.isUpdate) {
if(Label.ICS_Case_Interaction_Metrics.equals('1')) {
ICS_Case_Interactions_Trigger_Handler.insertInboundJive(map);
}
}
and in the controller you should have
public static void insertInboundJive(Map<Id, ICS_Case_Interaction__c> mapCases){
}

ResultSet doesn't return values for DB2, but it return values if I try to do it manualy

I'm trying to get values from resulset, but it return nothing.
When i'm trying to do it through plain sql it return some values.
List<String> res = new ArrayList<String>();
try {
String query = "SELECT COLUMN_NAME FROM idoc.columns_to_show where user = ? "
+ DAO.DB2_UR_POSTFIX;
Connection connection = Properties.getDocsConnection();
try {
PreparedStatement pr = connection.prepareStatement(query);
try {
pr.setString(1, user.getDomainName());
ResultSet rs = pr.executeQuery();
try {
while (rs.next()) {
res.add(rs.getString("COLUMN_NAME"));
}
} finally {
rs.close();
}
} finally {
pr.close();
}
} finally {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return res;
Don't use column name "user" it is reserved name for DB2 database.
Therefore I couldn't find any result.

What is the best way to get the max id of table?

What is the best way to get the max id of table? Below I have paste the error and code. So I was planning on using afterLast() method to get the max id but I get an error.
ERROR:
SQLException: feature not supported
Code:
public class ex03 {
public static void main(String[] args) {
String url = "jdbc:ucanaccess://C:/Users/dave_000/My_WorkSpace/Eclipse_Workspaces/workspace-jsp/T_01_JDBC_01.accdb";
Connection con;
// Get Max ID
Statement stmt0;
String query0 = "select * from user";
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
} catch (java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url, "", "");
stmt0 = con.createStatement();
// Get last ID
ResultSet rs = stmt0.executeQuery(query0);
rs.afterLast();
int maxID = rs.getInt("ID");
System.out.println(maxID);
pstmt1.close();
con.close();
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
}
It is much more efficient to use SQL to find the maximum value:
select max(id) from user

java.sql.SQLSyntaxErrorException: ORA-00936: missing expression error

I have made a database name enquiry which has got the details the code is showing the error misssing expression.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String d=jTextField1.getText();
String e=jTextField2.getText();
try
{
connect ob=new connect();
Connection con=ob.conn();
PreparedStatement pr=con.prepareStatement("select * from ENQUIRY where from=? and to=?");
pr.setString(1,d);
pr.setString(2,e);
ResultSet rs=pr.executeQuery();
boolean status=false;
while(rs.next())
{
status=true;
}
if(status==true)
{
new NewJFrame13().setVisible(true);
}
else
{
new NewJFrame5().setVisible(true);
}
super.dispose();
}
catch(Exception a)
{
System.out.println(a);
}
Using column names of from/to is probably not a good idea, as those are reserved words in oracle. You need to change the query to:
select * from ENQUIRY where "from"=? and "to"=?

preparedStatement.setNull(int parameterIndex, int sqlType)

Question #1
Could you anyone please tell me what is the benefit I will receive using the following code, when sPhoneExt is null ?
if (sPhoneExt == null || sPhoneExt.trim().equals("")) {
stmt.setNull(9, java.sql.Types.INTEGER);
} else {
stmt.setString(9, sPhoneExt);
}
Instead of stmt.setString(9, sPhoneExt);
Because iPhoneType = rset.getInt("phone_type"); will return 0 if the value is SQL NULL; which I don't want.
Question #2
And just curious stmt.setString(9, null) is performed what will be the return of rset.getInt("phone_type")?
Answer #2
getInt() will return zero when it is null in DB. You have to use the below code to know about DB NULL.
if (rs.wasNull()) {
// handle NULL field value
}
I don't see any benefit using setNull in this String case.
It is only used to check empty string "" and insert null in DB. But for that also we can do it like stmt.setString(9, null);
But when sPhoneExt is Integer and holding null, then We cannot perform
stmt.setInt(9, sPhoneExt); since setInt(int, int) API performs; converting (Unboxing) sPhoneExt (Integer) to primitive (int), so you will get NullPointerException. So you are in need of stmt.setNull(9, java.sql.Types.INTEGER);
Finally if you have inserted null in DB for NUMBER (sql type) column; getInt() will return 0 only.
This is irrespective of the below null set mechanism.
stmt.setString(9, null);
stmt.setNull(9, java.sql.Types.INTEGER)
Also Somebody told when the DB NUMBER column has default Value; that default value will be consider differently by the above two lines. But that is not true. Even that case also both the above line performs same way. It is setting NULL value; not the default value.
create table t1 (id number default 1 );
insert into t1 (id) values (2);
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class TestDB {
public static void main(String args[]) {
PreparedStatement stmt = null;
ResultSet rs = null;
Connection con = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#10.201.32.92:1521:psprd1", "username", "password");
String query = null;
String l = null;
ResultSet rset = null;
int paramIndex = 1;
query = "UPDATE t1 " + " SET id = ?";
stmt = con.prepareStatement(query);
stmt.setInt(paramIndex++, null);
// stmt.setNull(1, java.sql.Types.INTEGER);
stmt.executeUpdate();
stmt.close();
query = "select id from t1 ";
stmt = con.prepareStatement(query);
rset = stmt.executeQuery();
rset.next();
System.out.println(rset.getString("id"));
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

Resources