INSERT query not woking - java

<body>
<%# page import ="java.sql.*" %>
<%# page import="java.sql.Statement" %>
<%# page import="javax.sql.*" %>
<%# page import="java.sql.Connection" %>
<%# page import="java.sql.DriverManager" %>
<%
String pwd = request.getParameter("pass");
String email = request.getParameter("email");
Statement st,stt = null;
Connection con = null;
int i=0;
try {
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection("jdbc:postgresql://hostname","username", "Password");
stt = con.createStatement();
st = con.createStatement();
ResultSet rs;
rs = stt.executeQuery("select * from users where email='"+email+"'");
if (!rs.next()) {
ResultSet rss;
rss = st.executeQuery("insert into users(email,password) values ('"+email+"','"+pwd+"')");
if(rss.next()) {
response.sendRedirect("index.jsp");
out.print("Registration Successfull!"+"<a href='index.jsp'>Go to Login</a>");
}else {
response.sendRedirect("reg.jsp");
out.print("Registration was not Successfull!"+"<a href='reg.jsp'>Go to Registration</a>");
}
}else {
response.sendRedirect("reg.jsp?error=Email already exsist!");
}
}catch (Exception e) {
e.printStackTrace();
}
%>
</body>

Use executeUpdate for inserts, updates & delete,
executeQuery for select operations

Related

Image saved into database not showing

So i'm tryna save a blob image into database and display it once i click"view" href. But I don't know why the pic cannot be seen. It saves in mysql database tho...
retrieve_image.jsp:
<%# page import="java.sql.*,model.Upload,java.io.*,java.util.*" %>
<HTML>
<table border="1">
<tr><th>ID</th><th>Image</th></tr>
<%
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/backup","root","mysql");
Statement stmt=con.createStatement();
String strQuery = "select * from contacts";
ResultSet rs = stmt.executeQuery(strQuery);
while(rs.next()){
%>
<tr>
<td><%=rs.getInt("contact_id")%></td>
<td>
<img src="RetrieveImages.java?id=<%=rs.getInt(1)%>" width="100" height="100">
</a></td>
</tr>
<%
}
rs.close();
con.close();
stmt.close();
}
catch(Exception e)
{
e.getMessage();
}
%>
</table>
</HTML>
RetrieveImages is a servlet which has request dispatcher that goes to...
<%#page import="java.sql.Blob"%>
<%#page import="java.io.OutputStream"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%# page import="model.Upload" %>
<%
String contact_id = request.getParameter("contact_id");
String dbURL = "jdbc:mysql://localhost/backup";
String dbUser = "root";
String dbPass = "mysql";
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(dbURL, dbUser, dbPass);
PreparedStatement ps = con.prepareStatement("select * from contacts where contact_id=?");
ps.setString(1, contact_id);
ResultSet rs = ps.executeQuery();
if(rs.next()){
Blob blob = rs.getBlob("photo");
byte byteArray[] = blob.getBytes(1, (int)blob.length());
response.setContentType("image");
OutputStream os = response.getOutputStream();
os.write(byteArray);
os.flush();
os.close();
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(con != null){
try{
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
%>
In my java bean i have contact_id and photo as attribuites

java - jsp update database row via form on submit

Hi im trying to update data from database using submit button , witch is located on a jsp page that shows data based on name and surname that you entered in login.jsp..
validationForDatabase.jsp shows data from the table pacijent,based on name and surname are entered in another jsp page. Fields name and surname are readonly so you can chage everything except those fileds, and when you make chages and press button Update it should redirect you to update.jsp. If the update is successful you sholud be redirected back to validationForDatabase.jsp but instead of doing that it shows me Badly entered data from else section.
Could you please guide me on how to fix this problem or maybe another way to do this.
Thanks in advance
validationForDatabase.jsp
`
<%
try{
String name= request.getParameter("name");
String surname= request.getParameter("surname");
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection ("jdbc:mysql://localhost:3306/sth","root","");
PreparedStatement pst = conn.prepareStatement("Select name,surname from pacijent where name=? and surname=?");
pst.setString(1, name);
pst.setString(2, surname);
ResultSet rs = pst.executeQuery();
if(rs.next())
{
out.println("Name of the patient : "+name);
out.println("<br/>Surname of the patient : "+surname);
HttpSession sesija = request.getSession();
sesija.setAttribute("name", name);
sesija.setAttribute("surname", surname);
%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%
String connectionUrl = "jdbc:mysql://localhost:3306/sth";
try {Class.forName("com.mysql.jdbc.Driver");}
catch (ClassNotFoundException e) {e.printStackTrace();}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<form action="Update.jsp" method="get">
<%
try{
connection = DriverManager.getConnection ("jdbc:mysql://localhost:3306/sth","root","");
statement=connection.createStatement();
String sql ="SELECT name,father,surname,birth,adress,phone,email,notes "+ "FROM pacijent where name='"+sesija.getAttribute("name")+"'and surname='"+surname+"';";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
%>
<p align="center"><%= sesija.getAttribute("name")%><%= sesija.getAttribute("surname")%></p>
<p><label class="uname">name</label><input name="name" readonly value="<%=sesija.getAttribute("name") %>"/></p>
<p><label class="uname">father</label><input name="father" value="<%=resultSet.getString("father") %>"/></p>
<p><label class="uname">surname</label><input name="surname" readonly value="<%=sesija.getAttribute("surname") %>"/></p>
<p><label class="uname">birth</label><input name="birth" value="<%=resultSet.getString("birth") %>"/></p>
<p><label class="uname">Adress</label><input name="adress" value="<%=resultSet.getString("adress ") %>"/></p>
<p><label class="uname">phone</label><input name="phone" value="<%=resultSet.getString("phone") %>"/></p>
<p><label class="uname" > E-mail</label><input name="email" value="<%=resultSet.getString("email") %>"/></p>
<p><label for="usernamesignup" class="uname">info</label>
<textarea name="notes" id="a" class="a" rows="4" cols="60"
textareaObject.value="text" ><%= resultSet.getString("notes") %></textarea></p>
<input type="submit" name="Submit" value="Update" />
</form>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
sesija.invalidate();
%>
<%
}
else{
%>
<br/><br/><br/><br/><br/><h1 align="center">Badly entered data</h1>
<%}
}
catch(Exception e){
out.println("Error "+e);
}
%>`
Update.jsp works in redirecting back but it wont update data.
Update.jsp
`
<%
String name=request.getParameter("name");
String father=request.getParameter("father");
String surname=request.getParameter("surname");
String birth=request.getParameter("birth");
String adress =request.getParameter("adress ");
String phone=request.getParameter("phone");
String email=request.getParameter("email");
String notes=request.getParameter("notes");
try {
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sth", "root", "");
Statement st1 = null;
st1 = conn.createStatement();
HttpSession sesija = request.getSession();
sesija.setAttribute("name", name);
System.out.println(sesija.getAttribute(name));
st1.executeUpdate("UPDATE pacijent SET name= '"+name+"',father= '"+father+"',"
+ "surname= '"+surname+"',birth= '"+birth+"',adress = '"+adress +"',"
+ "phone= '"+phone+"',email = '"+email+"',notes = '"+notes+"'"
+ "WHERE name="+sesija.getAttribute(name));
response.sendRedirect("validationForDatabase.jsp");
} catch (Exception e) {
out.println("Error : " + e);
}
%>`
Thanks a lot.

Explain me some pieces of the following JSP code :

I am unable to get a piece of code in the following JSP code ( commented as d1, d2, d3, d4):
<%#page import="java.sql.*" errorPage="/MyError.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LoginProcess</title>
</head>
<body>
<%
Connection conn = null;
String uname = request.getParameter("uname");
String pass = request.getParameter("pass");
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e)
{
out.println("Error(class):"+e);
}
try
{
conn = DriverManager.getConnection("jdbc:mysql://localhost/studentdb","root","mysql");
PreparedStatement stmt = conn.prepareStatement("select * from studentdb.userdetails where uname=? and pass=?");
stmt.setString(1, uname);
stmt.setString(2, pass);
ResultSet rs = stmt.executeQuery();
if(!rs.next())
{
out.println("username or password is incorrect");
%> <%--d1--%>
Try Again:<%#include file="Login.html" %> <%--d2--%>
</body> <%--d3--%>
</html> <%--d4--%>
<%
return;
} //if
} //try-sql
catch(SQLException e)
{
out.println("Error(SQL):" + e);
}
finally
{
conn.close();
}
%>
This is Home Page<br>
Welcome,<b> <%= uname%></b>
</body>
the following are appearing in an if block which I am not getting why and how do they work , I know the meaning of <%#include file="Login.jsp"> and selective tags but not I am getting how are they workign here.
%> <%--d1--%>
Try Again:<%#include file="Login.html" %> <%--d2--%>
</body> <%--d3--%>
</html> <%--d4--%>
<%
(the body and html tags are not appearing in the above piece of code).
Instead of if(!rs.next()), try using if(rs.isBeforeFirst()). If rs.isBeforeFirst() is false, then you have no records.

No output on browser from my jsp page?

second.jsp
<%#page import="java.sql.*" %>
<html>
<body>
<%
try{
String id2=(request.getParameter("ID1"));
String url="jdbc:ucanaccess://C:\\Users\\Asim Iqbal\\Documents\\IT.accdb";
Connection conn = DriverManager.getConnection(url);
String sql= "SELECT * FROM Student WHERE ID=?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1,id2);
ResultSet rs = stmt.executeQuery();
if (rs.next())
{
int i=rs.getInt("ID");
String nam=rs.getString("Name");
String clas=rs.getString("Class");
String ph=rs.getString("Phone");
%>
<h1><%=i%></h1>
<h1><%=nam%></h1>
<h1><%=clas%></h1>
<h1><%=ph%></h1>
<%
}
} catch (SQLException e) {
e.printStackTrace();
}
%>
</body>
</html>
No output comes from DB in the browser..
Please give me suggestion where i am getting wrong...

Displaying data from ArrayList (EJB + Servlet + JSP(JSTL))

I have a stateless Session Bean in which I get the values ​​from the database and write them down in Arraylist, who returns to the servlet. In a servlet I send ArrayList on JSP page and try to show the value, but displays only the line "dataList", what is my mistake?
Here is my code:
ViewBean.java
//imports
#Stateless
#LocalBean
public class ViewBean {
public List getData() {
ResultSet rs = null;
List list = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/c_store", "root", "root");
Statement stmt = con.createStatement();
String query = "SELECT product.name_prod, product.price_prod, buy.number_buy, client.name_client, client.date_client FROM product, buy, client WHERE product.id_prod = buy.id_buy = client.id_client;";
stmt.executeQuery(query);
rs = stmt.getResultSet();
list = new ArrayList();
while(rs.next()){
list.add(rs.getString(1));
list.add(rs.getInt(2));
list.add(rs.getInt(3));
list.add(rs.getString(4));
list.add(rs.getString(5));
}
rs.close();
stmt.close();
con.close();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
ViewServlet.java
//imports
#WebServlet("/ViewServlet")
public class ViewServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB
ViewBean viewBean;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
List data = new ArrayList();
data = viewBean.getData();
request.setAttribute("dataList", data);
for(int i = 0; i<data.size(); i++){
out.println(data.get(i));
}
}
}
view.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>View Records</title>
</head>
<body>
<c:forEach var="item" items="dataList">
<b><c:out value="${item}" /></b>
</c:forEach>
</body>
</html>
You forgot to declare dataList as a variable, look at the items attribute in the loop:
<c:forEach var="item" items="${dataList}">
^ here is the bug, add the dollar sign and the curly braces
<b><c:out value="${item}" /></b>
</c:forEach>

Categories

Resources