Java: INSERT INTO inside a loop using Result Test - java

I am having a small problem while I try to insert some data in my database (MS - SQL).
I am using this code (I just copy-paste all of it, so someone might understand smth that I don't)
try
{
Connection connection = null;
Statement Statement = null;
ResultSet ResultSet = null;
String query = "";
// jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
String host = "jdbc:sqlserver://server;databaseName=db";
String username = "user";
String password = "pass";
Statement = connection.createStatement();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
DateFormat dateFormat1 = new SimpleDateFormat("dd.MM.yyyy");
Calendar cal1 = Calendar.getInstance();
for (int k = 0; k < idArray.length ; k ++ )
{
query = "INSERT INTO Companies (ID,Company,Company2,Company3,Country,ZIP,City,Street," +
"Phone,Fax,Email,Internet,CustomerNo,AccountMngr,Icon,AddressSource," +
"UserDefined1,UserDefined2,CreatedOn,CreatedBy,ColectedInformation) " +
" VALUES ('" + UUID.randomUUID() + "','" + company_nameArray[k]
+ "','" + company_name2Array[k] + "','" + company_name3Array[k] + "','DE','"
+ zipArray[k] + "','" + cityArray[k] + "','" + streetArray[k] + "','"
+ phone_Array[k] + "','" + faxArray[k] + "','" + emailArray[k] + "','"
+ internetArray[k] + "','" + customer_noArray[k]
+ "','d','131','60','Baufinder Import','Import Datum "
+ dateFormat1.format(cal1.getTime()) + "','"
+ dateFormat1.format(cal1.getTime()) + "','d','"
+ "cxcxvcx" +
"')";
ResultSet = Statement.executeQuery(query);
}
connection.close();
}
catch(NullPointerException e)
{
System.out.println("NullPointerException");
}
catch ( SQLException err )
{
System.out.println( "SQL Exception:" ) ;
// Loop through the SQL Exceptions
while( err != null )
{
System.out.println( "State : " + err.getSQLState() ) ;
System.out.println( "Message: " + err.getMessage() ) ;
System.out.println( "Error : " + err.getErrorCode() ) ;
err = err.getNextException() ;
}
}
catch( Exception e )
{
System.out.println( "There is a problem with " + e ) ;
}
}
and I am getting this error:
SQL Exception: State : null
Message: There was no result set returned by the statement.
Error : 0
I don't understand the problem with the result test. I have been using it a lot, since I try to read the data from another database and now I try to insert them to another.
Furthermore, all of these tables do not include null values.
Thank you in advance:)

Use Statement#executeUpdate(String) instead of Statement#execute(query);
for (int k = 0; k < idArray.length ; k ++ )
{
query = "INSERT INTO Companies (ID,Company,Company2,Company3,Country,ZIP,City,Street," +
"Phone,Fax,Email,Internet,CustomerNo,AccountMngr,Icon,AddressSource," +
"UserDefined1,UserDefined2,CreatedOn,CreatedBy,ColectedInformation) " +
" VALUES ('" + UUID.randomUUID() + "','" + company_nameArray[k]
+ "','" + company_name2Array[k] + "','" + company_name3Array[k] + "','DE','"
+ zipArray[k] + "','" + cityArray[k] + "','" + streetArray[k] + "','"
+ phone_Array[k] + "','" + faxArray[k] + "','" + emailArray[k] + "','"
+ internetArray[k] + "','" + customer_noArray[k]
+ "','d','131','60','Baufinder Import','Import Datum "
+ dateFormat1.format(cal1.getTime()) + "','"
+ dateFormat1.format(cal1.getTime()) + "','d','"
+ "cxcxvcx" +
"')";
int updatedRowCount = Statement.executeUpdate(query);
}
Notes:
Please consider using PreparedStatement to prevent possibility of SQL Injection if some data directly input by User.
Try to use batch insert if you need to improve performance of inserting.

Related

Execute java code inside java program using Nashorn

I have written a java code which will fetch the data from the table and show the output. This is basically a script that I want to run through Nashorn.
Below is the code I'm trying
public static void main(String args[]) throws ScriptException{
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
String script3 = "count = 0; "
+ "keyList = new java.util.ArrayList; "
+ "valueList = new java.util.ArrayList;"
+ "keyList.add('username'); "
+ "keyList.add('password'); "
+ "valueList.add('admin'); "
+ "valueList.add('admin');"
+ "java.lang.System.out.println('keyList :: ' + keyList); "
+ "java.lang.System.out.println('KeyValue :: ' + valueList);"
+ "sql = \" select * from credentials where 'isActive'='1'\";"
+ "java.lang.System.out.println('keyList.size() :: ' + keyList.size());"
+ "for (i = 0; i < keyList.size(); i++){"
+ " sql += and \\' + keyList.get(i) + \\' = \\' + valueList.get(i) + \\';}"
+ "java.lang.System.out.println('Search SQL : ' + sql); "
+ "con = GetConnected.connectToDatabase('my_db');"
+ "ps = con.prepareStatement(sql); "
+ "ps.setString(1, \"1\");"
+ "rs = ps.executeQuery(); "
+ "if (rs.isBeforeFirst()) {"
+ " count=1; "
+ " java.lang.System.out.println('Data is present in database'); "
+ "}"
+ "else "
+ " java.lang.System.out.println('Data is not present in database'); "
+ " rs.close(); " + " st.close(); " + " con.close(); ";
engine.eval(script3);
}
The error I'm getting is
Exception in thread "main" javax.script.ScriptException: <eval>:1:904 Missing close quote
count = 0; keyList = new java.util.ArrayList; valueList = new java.util.ArrayList;keyList.add('username'); keyList.add('password'); valueList.add('admin'); valueList.add('admin');java.lang.System.out.println('keyList :: ' + keyList); java.lang.System.out.println('KeyValue :: ' + valueList);sql = " select * from credentials where 'isActive'='1'";java.lang.System.out.println('keyList.size() :: ' + keyList.size());for (i = 0; i < keyList.size(); i++){ sql += and \' + keyList.get(i) + \' = \' + valueList.get(i) + \';}java.lang.System.out.println('Search SQL : ' + sql); con = GetConnected.connectToDatabase('my_db');ps = con.prepareStatement(sql); ps.setString(1, "1");rs = ps.executeQuery(); if (rs.isBeforeFirst()) { count=1; java.lang.System.out.println('Data is present in database'); }else java.lang.System.out.println('Data is not present in database'); rs.close(); st.close(); con.close();
^ in <eval> at line number 1 at column number 904
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:467)
at jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:534)
at jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:521)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:399)
at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
at com.engine.nashorn.Test.main(Test.java:87)
Caused by: jdk.nashorn.internal.runtime.ParserException: <eval>:1:904 Missing close quote
count = 0; keyList = new java.util.ArrayList; valueList = new java.util.ArrayList;keyList.add('username'); keyList.add('password'); valueList.add('admin'); valueList.add('admin');java.lang.System.out.println('keyList :: ' + keyList); java.lang.System.out.println('KeyValue :: ' + valueList);sql = " select * from credentials where 'isActive'='1'";java.lang.System.out.println('keyList.size() :: ' + keyList.size());for (i = 0; i < keyList.size(); i++){ sql += and \' + keyList.get(i) + \' = \' + valueList.get(i) + \';}java.lang.System.out.println('Search SQL : ' + sql); con = GetConnected.connectToDatabase('my_db');ps = con.prepareStatement(sql); ps.setString(1, "1");rs = ps.executeQuery(); if (rs.isBeforeFirst()) { count=1; java.lang.System.out.println('Data is present in database'); }else java.lang.System.out.println('Data is not present in database'); rs.close(); st.close(); con.close();
^
at jdk.nashorn.internal.parser.Lexer.error(Lexer.java:1706)
at jdk.nashorn.internal.parser.Lexer.scanString(Lexer.java:988)
at jdk.nashorn.internal.parser.Lexer.lexify(Lexer.java:1615)
at jdk.nashorn.internal.parser.AbstractParser.getToken(AbstractParser.java:132)
at jdk.nashorn.internal.parser.AbstractParser.nextToken(AbstractParser.java:211)
at jdk.nashorn.internal.parser.AbstractParser.nextOrEOL(AbstractParser.java:170)
at jdk.nashorn.internal.parser.AbstractParser.next(AbstractParser.java:157)
at jdk.nashorn.internal.parser.Parser.parse(Parser.java:281)
at jdk.nashorn.internal.parser.Parser.parse(Parser.java:249)
at jdk.nashorn.internal.runtime.Context.compile(Context.java:1286)
at jdk.nashorn.internal.runtime.Context.compileScript(Context.java:1253)
at jdk.nashorn.internal.runtime.Context.compileScript(Context.java:625)
at jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:532)
... 5 more
I think the place where the keyList and valueList value added to sql query it is giving problem.
sql += and \\' + keyList.get(i) + \\' = \\' + valueList.get(i) + \\';}"
that + will keep on adding until end of the script.

Update Query in GRN

This is a stock management system and I have a problem with updating part in good received note. When we purchase goods, we get a good received note, so when we get the items the number of items has to be updated (has to be added to the remaining goods) according to the item code.
According to the following code data from GRN will be extracted and will be saved in GRN1 and GRN2 tables. There's another table called Item_Supplier, when we receive goods Stock in hand field in Item_Supplier table has to updated according to the item_Id as well.
Problem is following code does not work.
Connection ss = Class_DB.myconnection();
Statement st = ss.createStatement();
-
ResultSet rs = st.executeQuery("select stock_in_hand from item_supplier where item_ID =('" + TF_GRN_ITEMID.getText() + "')");
grniid = TF_GRN_NO_OF_ITEM.getText();
while (rs.next()) {
nit = rs.getString("stock_in_hand");
}
sumn = grniid + nit;
st.executeUpdate("insert into grn1 values('" + TF_GRN_GRNNO.getText() + "','" + TF_GRN_SUPPLIERID.getText() + "','" + TF_GRN_AMOUNT.getText() + "','" + TF_GRN_DATE.getText() + "')");
st.executeUpdate("insert into grn2 values('" + TF_GRN_GRNNO.getText() + "','" + TF_GRN_ITEMID.getText() + "','" + TF_GRN_EXP_DATE.getText() + "','" + TF_GRN_TAX.getText() + "','" + TF_GRN_NO_OF_ITEM.getText() + "','" + TF_GRN_GAMOUNT.getText() + "','" + TF_GRN_NAMOUNT.getText() + "','" + TF_GRN_QTY.getText() + "','" + TF_GRN_UNIT.getText() + "','" + TF_GRN_FREE.getText() + "','" + TF_GRN_DIS.getText() + "')");
st.executeUpdate("update item_supplier set stock_in_hand='" + sumn + "' where item_ID='" + TF_GRN_ITEMID.getText() + "'");
JOptionPane.showMessageDialog(null, "Data Saved");
Please help.

Having Syntax Error in code java

Why is there a syntax error in this code?
String strSqlUpdate = "UPDATE Customers SET Contact = " + contact_num + ","
+ "Email = '" + email_add + "',"
+ "Address = '" + mail_add + "',"
+ "SurveyStatus = " + radio_group + ","
+ "Subscription = " + receive_info +
"WHERE membership_ID = '" + member_ID';
I thought my code was right.
If it is the error in your code, check all the variables that you have used are declared and initialized with proper values.
If it is the syntax of the sql that is bothering you , here is what your sql would look like if all the variables are initialized to null.
UPDATE Customers SET (Contact)null,Emailnull,Address,null,SurveyStatus,null,SubscriptionnullWHERE MembershipID =null
Use spaces in your strSqlUpdate to correct the above sql.
EDIT
What you need is something like this.
String strSqlUpdate = "UPDATE Customers SET Contact = " + contact_num
+ ",Email = '" + email_add + "'"
+ ",Address = '" + mail_add + "'"
+ ",SurveyStatus = '" + radio_group + "'"
+ ",Subscription = '" + receive_info + "' "
+ "WHERE membership_ID = '" + member_ID + "'";
I get no syntax errors when I declare and Initialize all of the variables. You have to make sure they're all initialized, within the scope of the strSqlUpdate
String contact_num = "";
String email_add = "";
String mail_add = "";
String radio_group = "";
String receive_info = "";
String member_ID = "";
String strSqlUpdate = " UPDATE Customers SET (Contact)" + contact_num + "," + "Email"
+ email_add + "," + "Address" + "," + mail_add + "," + "SurveyStatus" + "," + radio_group
+ "," + "Subscription" + receive_info + "WHERE MembershipID =" + member_ID;
Also considering you're talking about SQL syntax, adding on to what others have said, I'd advise you should use a PreparedStatement to avoid SQL injection.
PreparedStatement pst = conn.prepareStatement(
"UPDATE Customers SET (Contact) ?, ?, ?, ?, ?, ?, ? WHERE ? = ?");
pst.setString(1, contact_num);
pst.setString(2, email_add);
... and so on
An error in your current SQL syntax is this
"Subscription" + receive_info + "WHERE MembershipID
Translated as
"...Subscrptionreceive_infoWHERE MembershipID..."
You need to add spaces wherever you don't have commas

Application is getting stuck at hibernate txOracle.commit();

try {
sessionOracle = BaseDAO.getHibernateSession().openSession();
sessionPostgres = BaseDAOgis.getHibernateSession().openSession();
int id = 0;
JSONArray jaRoute = new JSONArray();
for (int i = 0; i < dataHolder.size(); i++) {
JSONObject jo = new JSONObject();
try{
jo.put("routeNo", (int) list.get(0));
jo.put("routeName", list.get(1).toString());
jo.put("stopSequenceID", (int) list.get(2));
jo.put("stopID", (int) list.get(3));
jo.put("stopName", list.get(4).toString());
jo.put("lat", (double) list.get(5));
jo.put("lon", (double) list.get(6));
System.out.println(jo.length() + "" +cellStoreVector.size());
if(jo.length()!=cellStoreVector.size())
{
System.out.println(jo.length() + "if" +cellStoreVector.size());
joOutput.put("success", true);
joOutput.put("error", true);
joOutput.put("size", false);
return joOutput;
}
}
catch(Exception e){
System.out.println("EXCEWs");
System.out.println(e);
joOutput.put("success", true);
joOutput.put("error", true);
joOutput.put("size", false);
return joOutput;
}
jaRoute.put(jo);
}
System.out.println("DB");
txPostgres = sessionPostgres.beginTransaction();
txOracle= sessionOracle.beginTransaction();
for (int i = 0; i < jaRoute.length(); i++) {
direction = "U";
JSONObject first = jaRoute.getJSONObject(i);
routeNo = first.getString("routeNo");
System.out.println();
int no = Integer.parseInt(routeNo);
routeName = first.getString("routeName");
stopSequenceID = first.getString("stopSequenceID");
stopID = first.getString("stopID");
stopName = first.getString("stopName");
lat = first.getString("lat");
lon = first.getString("lon");
if(i < jaRoute.length() - 1)
second = jaRoute.getJSONObject(i + 1);
System.out.println("id"+ id);
if(Integer.parseInt(first.getString("routeNo"))!= id){
try{
String sqlRouteMaster = "insert into route_master(route_id, route_name, direction, route_status, route_no, ROUTE_EFCTV_FROM_DT,Source_stop_id,dest_stop_id,ROUTE_TYPE,city_operational) "
+ "values('"
+ routeNo
+ "','"
+ routeName
+ "','"
+ direction1
+ "','"
+ routeStatus
+ "','"
+ routeName.trim().substring(0, 9)
+ "',now(),'"+1038+"','"+1039+"','"+37+"','"+false+"')";
String sqlMRoute="insert into m_route(route_id, route_name, direction, route_status, route_no, ROUTE_EFCTV_FROM_DT,source_stop_id, dest_stop_id,ROUTE_TYPE,CITY_TYPE) "
+ "values('"
+ routeNo
+ "','"
+ routeName
+ "','"
+ direction
+ "','"
+ routeStatus
+ "','"
+ routeName.trim().substring(0, 9)
+ "', current_timestamp,'"+1038+"','"+1039+"','"+37+"','"+97+"')";
int list4=sessionPostgres.createSQLQuery(sqlRouteMaster)
.executeUpdate();
System.out.println(list4);
int list5=sessionOracle.createSQLQuery(sqlMRoute).executeUpdate();
System.out.println(list5);
}catch(Exception ii){
}finally{}
if(Integer.parseInt(second.getString("routeNo")) == id || id == 0){
double endLat = Double.parseDouble(second
.getString("lat"));
double endLon = Double.parseDouble(second
.getString("lon"));
theGeom = getMultiLineString(startLat, startLon,
endLat, endLon);
if (theGeom.length() > 0) {
System.out.println("rout");
sqlRouteDetails = "insert into route_details(route_seq_no,route_id,stop_seq_no,stop_id,location,lat,lon,the_geom,stop_type_id,REF_DISTANCE,REF_TIME,STOP_TIME)"
+ " values('"
+ routSeqNo
+ "','"
+ routeNo
+ "','"
+ stopSequenceID
+ "','"
+ stopID
+ "','"
+ stopName
+ "','"
+ lat
+ "','"
+ lon
+ "',ST_SetSRID(ST_GeomFromText('"
+ theGeom
+ "'),4326),'"
+ stopTypeId
+ "','"
+ refDistance
+ "','" + refTime + "','" + stopTime + "')";
} else {
System.out.println(id);
sqlRouteDetails = "insert into route_details(route_seq_no,route_id,stop_seq_no,stop_id,location,lat,lon,stop_type_id,REF_DISTANCE,REF_TIME,STOP_TIME)"
+ " values('"
+ routSeqNo
+ "','"
+ routeNo
+ "','"
+ stopSequenceID
+ "','"
+ stopID
+ "','"
+ stopName + "','" + lat + "','" + lon + "','"+stopTypeId+"','"+refDistance+"','"+refTime+"','"+stopTime+"')";
}
id=Integer.parseInt(first.getString("routeNo"));
String sqlMRouteDtl="insert into m_route_dtl(route_seq_no,route_id, stop_seq_no, stop_id,stop_type_id,REF_DISTANCE,REF_TIME,STOP_TIME) "
+ "values('"+mRouteSql+"','"+routeNo+"','"+stopSequenceID+"','"+stopID+"','"+stopTypeId+"','"+refDistance+"','"+refTime+"','"+stopTime+"')";
sessionPostgres.createSQLQuery(sqlRouteDetails).executeUpdate();
sessionOracle.createSQLQuery(sqlMRouteDtl).executeUpdate();
routSeqNo++;
}
//
txOracle.commit();
//
txPostgres.commit();
joOutput.put("success", true);
joOutput.put("error", false);
} catch (Exception i) {
i.printStackTrace();
//
txPostgres.rollback();
//
txOracle.rollback();
joOutput.put("success", false);
joOutput.put("error", false);
} finally {
try {
sessionPostgres.close();
sessionOracle.close();
} catch (Exception e) {
e.printStackTrace();
}
return joOutput;
}
}
forthe first time or twice , appLicaton is running fine but if we are trying For next time it is stuck at
Hibernate: insert into m_route(route_id, route_name, direction, route_status, route_no, ROUTE_EFCTV_FROM_DT,source_stop_id, dest_stop_id,ROUTE_TYPE,CITY_TYPE) values(?,?,?,?,?,?,?,?,?,?,?)
And again we are restarting Oracle db then again same thing. once or twice running and stuck.
please help me.
Thanks in advance.
I could not able to find the problem. Why its locking/ postgres and oracle.
route_master and route_details are Postgres tables and
m_route and m_route_dtl
are Oracle tables
First of all why you are using plain sql when have Hibernate in the project? its just not efficient.
Second based on code you provided you opening new hibernate session each time, try initilize it just once.
Finally can you log on admin account on oracle/postgres and check what is actually going on when apllication gets stuck ?

Writing the resultset to csv file

I have a method getstaffinfo, which has 3 parameter (var_1, connection, filewriter fw), the var_1 value is read from a text file. So the method will be called as many times based on all the var_1 value passed from text file . approx ( 15000)
public static String getstaffid(String var_1, Connection connection,
FileWriter fw) throws SQLException, Exception
// Create a statement
{
String record = null;
ResultSet rs = null;
Statement stmt = connection.createStatement();
boolean empty = true;
try {
rs = stmt
.executeQuery("select username, firstname, lastname, middlename, street, city, stateorprovince, ziporpostalcode, countryorregion, fax, phone, extension, mobile, pager, title, primaryemail, secondaryemail, officename, description, comments, suspendeddate, userdata, employeeid, createuser, updateuser, createdate, updatedate, employeetype, servicedeskticketnumber, startdate, enddate, manager, businessapprover, technicalapprover, delegate, location, jobcodes, customproperty1, customproperty2, customproperty3, customproperty4, customproperty5, customproperty6, customproperty7, customproperty8, customproperty9, customproperty10 from globalusers where username = '"+ var_1 + "'");
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
ArrayList<String> records = new ArrayList<String>();
while (rs.next()) {
empty = false;
//record = rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " + rs.getString(4) + " " + rs.getString(5) + " " + rs.getString(6) + " " + rs.getString(7) + " " + rs.getString(8) + " " + rs.getString(9) + " " + rs.getString(10) + " " + rs.getString(11) + " " + rs.getString(12) + " " + rs.getString(13) + " " + rs.getString(14) + " " + rs.getString(15) + " " + rs.getString(16) + " " + rs.getString(17) + " " + rs.getString(18) + " " + rs.getString(19) + " " + rs.getString(20) + " " + rs.getString(21) + " " + rs.getString(22) + " " + rs.getString(23) + " " + rs.getString(24) + " " + rs.getString(25) + " " + rs.getString(26) + " " + rs.getString(27) + " " + rs.getString(28) + " " + rs.getString(29) + " " + rs.getString(30) + " " + rs.getString(31) + " " + rs.getString(32) + " " + rs.getString(33) + " " + rs.getString(34) + " " + rs.getString(35) + " " + rs.getString(36) + " " + rs.getString(37) + " " + rs.getString(38) + " " + rs.getString(39) + " " + rs.getString(40) + " " + rs.getString(41) + " " + rs.getString(42) + " " + rs.getString(43) + " " + rs.getString(44) + " " + rs.getString(45) + " " + rs.getString(46) + " " + rs.getString(47);
for (int i = 1; i <= columns; i++) {
String value = rs.getString(i);
records.add(value);
}
for (int j = 0; j < records.size(); j++) {
record = records.get(j) + ",";
}
fw.append(record);
}
/*fw.append(rs.getString(1));
fw.append(',');
fw.append(rs.getString(2));
fw.append(',');
fw.append(rs.getString(3));
fw.append('\n'); */
} finally {
fw.flush();
rs.close();
stmt.close();
}
return record;
}
As you can see, am executing a query for 47 values, which could be null or it can have some value.
Then i iterate through this 47 column, take the value and store it to an array list. Then i iterate the array list and write all the values to the string record with comma seperated value. Which is written to a csv file.
But it does not work fine. Any inputs would be appreciated...
You may have already solved the problem. Just let you know that I tried to use your code just now and found the issue was here:
record = records.get(j) + ",";
You should use something like this:
record = record + records.get(j) + ",";
Also change String to StringBuffer will improve the performance.
You didn't write the exact problem you face, but there is one for sure: you never write a line break into the file, so all data gets in one line.
while (rs.next()) {
... // your code, with the for loops
fw.append(record); //writing out the line, from your code
fw.append("\r\n"); //line break -- add this line
} //this is the end of the "while(rs.next())" loop
...

Categories