My delete statement is not working i am trying to delete duplicate row if user have entered more than one product_id and user_id but the delete is not working at all.
I tried entering one row multiple time and hasNext returns true, goes over if but doesn't execute delete and alert
Code:
<%--
Document : cart
Created on : Apr 24, 2020, 3:43:01 PM
Author : user
--%>
<%#page import="java.sql.CallableStatement"%>
<%#page import="java.sql.SQLException"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String username=(String)session.getAttribute("username");
String product_id=request.getParameter("id");
Connection con=null;
Statement stmt=null;
Statement stmt1=null;
Statement stmt2=null;
try{
Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","admin","admin");
}
catch(ClassNotFoundException e){
System.out.println("Class not found :"+e.getMessage());
}
try{
int user_id=0;
stmt=con.createStatement();
stmt1=con.createStatement();
stmt2=con.createStatement();
//check for duplicate rows to avoid user adding to cart the same item again.
ResultSet rs=stmt.executeQuery("SELECT user_id FROM users where user_name='"+username+"'");
while(rs.next()){
user_id=Integer.valueOf(rs.getString(1));
System.out.println(user_id);
}
stmt1.executeUpdate("INSERT INTO transaction (user_id,product_id) values('"+user_id+"','"+product_id+"')");
ResultSet rs_check=stmt.executeQuery("SELECT '"+user_id+"','"+product_id+"', COUNT(*) occurences from transaction GROUP BY '"+user_id+"','"+product_id+"' HAVING COUNT(*) > 1 ");
//check for duplicate rows after insert and then delete that row
System.out.println(rs_check.next());//1)false
boolean hasNext=rs_check.next();
if(hasNext){
//stmt2.executeUpdate("delete from transaction where user_id='"+user_id+"' and product_id='"+product_id+"'");
CallableStatement ctmt=con.prepareCall("{call delete_dup(?,?)}");
ctmt.setInt(1,user_id);
ctmt.setInt(2,Integer.valueOf(product_id));
ctmt.execute();
%><script>alert("you have added the item before?");</script><%
}
}
catch(SQLException e){
System.out.println("SQL Exception: "+e.getMessage());
}
%>
</body>
</html>
Try to add a commit after the insert to check if this works like :
con.commit();
If this solve the problem you have to set : con.setAutoCommit(true);, if you don't want to use Oracle commit/rollback feature.
Related
I am using a servlet(servlet1) via a GET method from httpurlconnection() function in order to get the XML generated by an another servlet(servlet2) connected to a postgreSQL Database.
The XML generated by the servlet2 via the statement:
select query_to_xml('select * from test', true, false, '');
I initialize an httpurlconnection() from servlet1 to servlet2 and I stored in a string "response1" the output like that:
String inputLine;
StringBuffer response1 = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response1.append(inputLine);
}
in.close();
//The output in console
System.out.println(response1.toString());
The XML is stored in the string "response1" as:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link type="text/css" rel="stylesheet" href="/pro/inc/form.css;jsessionid=D965FA3338EC4E88F6F7AA0B64308446" />
</head>
<body>
<p><alltests_00_with_defects xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<row>
<n5>a</n5>
<n4>b</n4>
<n3>c</n3>
<n2>d</n2>
<n1>e</n1>
<row>
<row>
<n5>a</n5>
<n4>b</n4>
<n3>c</n3>
<n2>d</n2>
<n1>e</n1>
<row>
</html>
Until here, it's cool!!
Now, I am looking for a solution that can convert BACK the XML generated to data values.
Any ideas?
Hi I am trying to create an INSERT INTO script in Dreamweaver Command and ASP.
If I use a static value it works fine, but when I try to declare a variable I get the following error message
Microsoft OLE DB Provider for ODBC Drivers error '80040e14'
[Sybase][ODBC Driver][Adaptive Server Anywhere]Primary key for table 'testing'
is not unique
/coding/Untitled-3.asp, line 30
Now the reason it is telling me the primary key is not unique is it is passing a null value, rather than the value of my field. Code below;
<%#LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
Dim Command1__product
Command1__product = Request.Form("product")
%>
<!--#include file="Connections/Conn_PSCRM_Demo.asp" -->
<%
' IIf implementation
Function MM_IIf(condition, ifTrue, ifFalse)
If condition = "" Then
MM_IIf = ifFalse
Else
MM_IIf = ifTrue
End If
End Function
%>
<%
Set Command1 = Server.CreateObject ("ADODB.Command")
Command1.ActiveConnection = MM_Conn_PSCRM_Demo_STRING
Command1.CommandText = "INSERT INTO testing (prodref) VALUES (?)"
Command1.Parameters.Append Command1.CreateParameter("product", 201, 1, 25, MM_IIF(Request.Form("Field1") , Request.Form("Field1") , Command1__product & ""))
Command1.CommandType = 1
Command1.CommandTimeout = 0
Command1.Prepared = true
Command1.Execute()
%>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form action="" method="post" name="form" id="form">
<label for="Field1"></label>
<input name="Field1" type="text" id="Field1" value="33399">
</form>
</body>
</html>
According to my comment - you'll have to check if your form has been posted or your site has just been initially loaded. In your question the code will be executed everytime the site has been loaded - that's why it works when you provide hardcoded values.
Anything like this code will do the trick
<%#LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
If Request.Form("SUBMITBUTTON") <> "" then
Dim Command1__product
Command1__product = Request.Form("product")
' all your code goes here!
%>
Bit of a rookie error, I wasn't declaring the form variable.
I have added a Bindings Request.Form and all is working.
I am trying to follow a tutorial online and I have followed the steps exactly however i keep getting an error when trying to write to a database.
Here Is the code for a simple form
#{
var name = string.Empty;
var email = string.Empty;
var subject = string.Empty;
var message = string.Empty;
if (IsPost){
name = Request["txtName"];
email = Request["txtEmail"];
subject = Request["txtSubject"];
message = Request["txtMessage"];
var db = Database.Open("FormAndDataDB");
db.Execute("INSERT INTO ContactLog (Name, Email, Subject, Message, DateSent) " +
"VALUES (#0, #1, #2, #3, #4)", name, email, subject, message, DateTime.Now);
}
}
<doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="contact.cshtml" method="POST">
<p>
<label for="txtName">Name:</label><br />
<input type="text" name="txtName" id="txtName" value="#name"/>
</p>
<p>
<label for="txtEmail">Email:</label><br />
<input type="text" name="txtEmail" id="txtEmail" value="#email" />
</p>
<p>
<label for="txtSubject">Subject:</label><br />
<input type="text" name="txtSubject" id="txtSubject" value="#subject" />
</p>
<p>
<label for="txtMessage">Message:</label><br />
<textarea name="txtMessage" id="txtMessage" cols="40" rows="10" >#message</textarea>
</p>
<p>
<input type="submit" value="send" />
</p>
</form>
</body>
</html>
Here is the error i get in visual studio on attempt of execution of the SQL insert statement:
"An exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in System.Data.SqlServerCe.dll but was not handled in user code"
This is the error text returned from SQL and displayed on the webpage:
"The column cannot contain null values. [ Column name = ID,Table name = ContactLog ]"
I have filled out the form completely
Your errors in the question notwithstanding, the problem seems to be that you've got a table (contactLog) with a column (id) that has the NOT NULL attribute attached to it. You are trying to insert a row without a value in said column, and that is causing this error.
To fix this either insert a value into the [ID] column or set the identity attribute to TRUE instead of FALSE on said column and allow it to autogenerate / autoincrement.
My assumption is that even when you fixed the syntax of the insert statement you still couldn't process the insert properly.
You have five columns, but only 3 values.
Your statement is
INSERT INTO ContactLog (Name, Email, Subject, Message, DateSent)
VALUES (#0, #1, #3)
What happened to #2 and #4?
Maybe you need
db.Execute("INSERT INTO ContactLog (Name, Email, Subject, Message, DateSent) "+
"VALUES (#0, #1, #2, #3, #4)",
name, email, subject, message, DateTime.Now);
I am currently having a problem with some thumbnail images in a classic ASP website. Essentially, I have a database in Microsoft Access that contains three tables: One with the pictures and their info, another that is linked to the pictures table and contains location information and a third table which just has some text for the website.
On the page which is coded below, each image in the database has its corresponding thumbnail printed onto the page. The user can then click on the thumbnail and be taken to the larger image with some associated information.
My problem is that the thumbnails are repeating themselves, up to 11 times.
<% option explicit %>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Places</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<!-- #include file="conn.asp" -->
<div id="container">
<!-- #include file="nav.asp" -->
<% dim SQL, info
' 0 1 2 3 4
SQL = "select PicturesTable.id, filename, location, title, description"&_
" from PicturesTable, locationsTable"&_
" where PicturesTable.locationNum = locationsTable.id"&_
" order by locationsTable.id"
set info=conn.execute(SQL)
This is my loop where I think the problem is.
if info.eof then
response.write "No data found."
end if
do until info.eof
response.write "<a href=""images.asp?i=" & info(1) & """>" &_
"<img src=""thumbs/" & info(1) & """></a>"
info.movenext
loop
%>
</div>
<%
conn.close
%>
</body>
</html>
So the problem was in fact that I had designed the database poorly in access and I was repeating the records when they should have been unique. Hence, the repeated images. Deleting the repeated records gave me the solution. Thanks for the help anyway.
Try the following SQL instead; the problem is likely that you need to JOIN the two tables.
SQL = "SELECT PicturesTable.id, filename, location, title, description"&_
" FROM PicturesTable"&_
" LEFT JOIN locationsTable"&_
" ON PicturesTable.locationNum = locationsTable.id"&_
" ORDER BY locationsTable.id
Using:
select name, id
from "TEST"
where id :2
AND name :1
order by id desc
I am getting ORA: 00904 "TEST"."NAME": invalid identifier error but the wierd part is that I have checked my test table and it does not have NAME field but it has name field, I have also checked all the references which is made from that table and all other constraints but still it gives me same error. I do not know why, is there a way where I can check all the columns of the database for NAME column name or any other debuggind approach recommended would be highly welcomed.
DESC TEST;
Name Null Type
id NOT NULL NUMBER(11)
name VARCHAR2(29)
2 rows selected
EDIT
DESC TEST
Name Null Type
------------------------------ -------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ID NOT NULL NUMBER(11)
NAME VARCHAR2(29)
2 rows selected
Java Code
public String searchExecute(HttpServletRequest req, javax.servlet.ServletContext ctx, String nextPage){
// ESCA-JAVA0266:
System.out.println("This is Awesome");
// ESCA-JAVA0266:
System.out.println("id:"+req.getParameter("s_1985"));
// ESCA-JAVA0266:
System.out.println("name:"+req.getParameter("s_1984"));
boolean bDisplayAll = StringUtils.stringToBoolean(req.getParameter("display_all"));
if(bDisplayAll)
// ESCA-JAVA0034:
req.setAttribute("c_display_all", "Y");
req.setAttribute("c_search_submitted", "Y");
return nextPage;
}
JSP Code
<%# page import="att.leadx.dbutils.AppUtils" %>
<%# page import="java.util.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-
1">
</head>
<link rel=stylesheet type=text/css href="leadx.css">
<body bgcolor="#FFFFFF"><BR>
<form NAME="forma" ACTION="dispatcher" METHOD="post">
<INPUT TYPE="hidden" name="action" value="">
<input type=hidden name="c_master" value="TEST_SEARCH">
<%
request.setAttribute("c_form", "TEST_SEARCH");
request.setAttribute("c_top_title","PROFILE > TEST_SEARCH");
request.setAttribute("c_top_link_image","images/setup_sm.gif");
request.setAttribute("c_top_link_action","user.search.setup");
request.setAttribute("c_top_link_app_func","search_setup");
request.setAttribute("c_top_link_alt_display","Setup search criteria");
%>
<jsp:include page="j_custom_search.jsp" flush="true" />
<table width="94%" border="0" cellspacing="1" cellpadding="3" align=center>
<tr>
<td colspan=4 align=center>
<INPUT TYPE="submit" value="Search" class=prismsbutton onclick="document.forma.action.value ='cep.project.search.execute'">
</td>
<td colspan=4 align=center>
<INPUT TYPE="button" value="Cancel" class=prismsbutton onclick="window.history.back()">
</td>
</tr>
</table>
</form>
<form NAME="formd" ACTION="dispatcher" METHOD="post">
<input type="hidden" name="c_jsp" value="j_test_dynamic_search.jsp">
<%
request.setAttribute("c_master", "TEST_SEARCH");
request.setAttribute("c_html_form","formd");
request.setAttribute("c_list_id","1984");
request.setAttribute("c_search_form","TEST_SEARCH");
Object args[] = att.utils.DataStore.arg(att.leadx.dbutils.AppUtils.getLoggedInUser(request), att.utils.DataStore.TYPE_NUMERIC);
request.setAttribute("c_args", args);
if (att.utils.StringUtils.stringToBoolean((String)request.getAttribute("c_search_submitted"))){
%>
<jsp:include page="j_master_detail_dlist.jsp" flush="true" />
<%
}
%>
</form>
<%!
private void o(String s){
if (att.leadx.dbutils.AppUtils.inDebug())
System.out.println("[J_USER_SEARCH.JSP] " + s);
}
%>
SQL Statement
select name, id from TEST where name = :1 AND id = :2 order by id desc
Error Message
Aug 16, 2010 5:22:21 PM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet jsp threw exception
java.sql.SQLException: ORA-00936: missing expression
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:180)
at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:208)
at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:543)
at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1451)
at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteDescribe(TTC7Protocol.java:651)
at oracle.jdbc.driver.OracleStatement.doExecuteQuery(OracleStatement.java:2110)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2324)
at oracle.jdbc.driver.OracleStatement.executeQuery(OracleStatement.java:627)
at att.utils.DataStore.retrieve(DataStore.java:724)
at org.apache.jsp.j_005fmaster_005fdetail_005fdlist_jsp._jspService(j_005fmaster_005fdetail_005fdlist_jsp.java:566)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:308)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:259)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:659)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:565)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:493)
at org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:965)
at org.apache.jsp.j_005ftest_005fdynamic_005fsearch_jsp._jspService(j_005ftest_005fdynamic_005fsearch_jsp.java:102)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:308)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:259)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:659)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:457)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:395)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:311)
at att.leadx.nav.Dispatcher.service(Dispatcher.java:113)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:470)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:879)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Unknown Source)
Thanks
SELECT *
FROM ALL_TAB_COLS
WHERE UPPER(COLUMN_NAME) = 'NAME';
will show you all columns called NAME
EDIT:
Based on your comment, aren't you missing the operators in your WHERE clause? ie =
select name, id
from "TEST"
where id :2 -- Surely you mean: id = :2
AND name :1 -- Surely you mean: name = :2
order by id desc
EDIT 2:
Based on the SQL*Plus output, it looks like you've created the table with lower-case column names. Whilst this is possible and valid it's usually just hard work. I'd recreate the columns with upper case names. (as Alex said)
EDIT 3:
I think...
SELECT "id", "name"
FROM TEST
WHERE "id" = :1
AND "name" = :2
ORDER BY "id" desc;
should work
It's a good idea not to surround column and table names with double-quotation marks unless you are know what you are doing and confident you need that.
In Oracle, database object names (including table and columns) are not case-sensitive and assumed upper-case unless you include them into double-quotes.
E.g, if a table created as TEST, it can be referred to as test, Test or TesT or "TEST".
But if it is created as "Test", you will only be able to refer to it as "Test" (in double quotation marks). All the other ways will result in "invalid identifier" error.