Share on Google+Share on Google+

Pradeep
insertuploadimahe
2 Answer(s)      7 years ago
Posted in : JDBC
i having a 4 textbox and 3 imagetextbox so how i can enter this data in database using servlet

Ads

View Answers

February 23, 2010 at 8:42 AM


Sorry i donot know about imagetextbox so i will give sample code to how to insert image and other data to databse.
I'm using netbeans ide to create this example and enterprisedb to as my database and glassfish v2 as my application server.

Sample table script below.(this script may vary if you use other data base such as oracle ,mysql,sql server ...)

---------------------------------------------------------------------------
-- Table: sample_data

-- DROP TABLE sample_data;

CREATE TABLE sample_data
(
name character varying(15) NOT NULL,
age integer NOT NULL,
year integer NOT NULL,
image bytea NOT NULL,
primary key (name)
)

---------------------------------------------------------------------------

To retrieve values from jsp components(textboxes )you can use
request.getParameter(param name ) method .

Sample jsp code is below.

<[email protected] contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>JSP Page</title>
</head>
<body><form action="processData">
<input type="text" name="name" value="" />
<input type="text" name="age" value="" />
<input type="text" name="year" value="" />
<input type="submit" value="Submit" />
</form>
<h1>Hello World!</h1>

</body>
</html>

---------------------------------------------------------------------------
Sample Dbcon class is below



import java.sql.Connection;
import java.sql.DriverManager;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;

/**
*
* @author pradeep
*/
public class DBCon {

public Connection getDBCon() {
Connection con = null;
Context ctx=null;
try {
Class.forName("com.edb.Driver");

con = DriverManager.getConnection("jdbc:edb://192.168.1.136:5444/testhr";, "enterprisedb", "olimpus");


return con;
} catch (Exception e) {
e.printStackTrace();
Logger l = Logger.getLogger("Db Connection");
l.log(Level.SEVERE, e.getMessage());
}
return null;
}



}

---------------------------------------------------------------------------
Sample DbProcess Class is below.

import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
*
* @author pradeep
*/
public class DBProcess {

public int saveData(String name, int age, int year, String path) throws SQLException {
Connection c = null;
PreparedStatement ps = null;
String sql = "insert into mytbale(name,age,year,image) values(?,?,?,?)";
try {
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
DBCon bCon = new DBCon();
c = bCon.getDBCon();
ps = c.prepareStatement(sql);
ps.setString(0, name);
ps.setInt(1, age);
ps.setInt(2, year);
int r = Integer.parseInt("" + file.length());
ps.setBinaryStream(4, fis, r);
ps.executeUpdate();
ps.close();
fis.close();
c.close();

return 0;

} catch (Exception e) {
e.printStackTrace();
return -1;
}finally{
if(ps!=null){
ps.close();
}
if(c!=null){
c.close();
}
}
}
}

---------------------------------------------------------------------------
Sample Servlet is below.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package pck;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*
* @author pradeep
*/
public class processData extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {

String name=request.getParameter("name");
int age=Integer.parseInt(request.getParameter("age"));
int year=Integer.parseInt(request.getParameter("year"));
String imgpath="";
//for image get image path in your server app get image path
DBProcess bProcess=new DBProcess();
int result= bProcess.saveData(name, age, year, imgpath);
//display status of the statement
if(result==0){
//display success msg
}else{
//display error msg
}


} catch (SQLException ex) {
Logger.getLogger(processData.class.getName()).log(Level.SEVERE, null, ex);
} finally {
out.close();
}
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

}

If you need more exsample on netbeans vist http://netbeans.org/kb/index.html page .
Best regards.


February 23, 2010 at 3:16 PM


Hi Friend,

Try the following code:

1)form.jsp:
<html>
<body>
<form name="userform" method="post" action="../Servlet">
<table>
<tr><td>Enter Name:</td><td><input type="text" name="name"></td></tr>
<tr><td>Enter Address:</td><td><input type="text" name="address"></td></tr>
<tr><td>Enter Phone Number:</td><td><input type="text" name="phoneno"></td></tr>
<tr><td>Enter Email:</td><td><input type="text" name="email"></td></tr>
<tr><td>Image1:</td><td><input type="file" name="image1"></td></tr>
<tr><td>Image2:</td><td><input type="file" name="image2"></td></tr>
<tr><td>Image3:</td><td><input type="file" name="image3"></td></tr>
<tr><td><input type="submit" value="Submit"></td></tr>
</table>
</form>
</body>
</html>

2)Servlet.java:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Servlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{
PrintWriter out = response.getWriter();
String name=request.getParameter("name");
String address=request.getParameter("address");
String no=request.getParameter("phoneno");

int phoneNo=Integer.parseInt(no);
String email=request.getParameter("email");
String image1=request.getParameter("image1");
String image2=request.getParameter("image2");
String image3=request.getParameter("image3");


Connection connection = null;
String connectionURL = "jdbc:mysql://localhost:3306/register";;
ResultSet rs = null;
PreparedStatement psmnt = null;

try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "root");
File f1 = new File(image1);
FileInputStream fis1 = new FileInputStream(f1);

File f2 = new File(image2);
FileInputStream fis2 = new FileInputStream(f2);

File f3 = new File(image3);
FileInputStream fis3 = new FileInputStream(f3);
psmnt = connection.prepareStatement("insert into person(name,address,phoneNo,email,image1,image2,image3) values(?,?,?,?,?,?,?)");
psmnt.setString(1,name);
psmnt.setString(2,address);
psmnt.setInt(3,phoneNo);
psmnt.setString(4,email);
psmnt.setBinaryStream(5, (InputStream)fis1, (int)(f1.length()));
psmnt.setBinaryStream(6, (InputStream)fis2, (int)(f2.length()));
psmnt.setBinaryStream(7,(InputStream)fis3, (int)(f3.length()));
int s = psmnt.executeUpdate();
if(s>0) {
System.out.println("Uploaded successfully !");
}
else{
System.out.println("unsucessfull to upload file.");
}
}
catch(Exception e){e.printStackTrace();}
}
}

For the above code, we have create a table named 'person'
CREATE TABLE `person` (
`id` bigint(255) NOT NULL auto_increment,
`name` varchar(255) default NULL,
`address` varchar(255) default NULL,
`phoneNo` int(255) default NULL,
`email` varchar(255) default NULL,
`image1` longblob,
`image2` longblob,
`image3` longblob,
PRIMARY KEY (`id`)
)
Thanks









Related Tutorials/Questions & Answers:
Tutorials   
Java Spring Hibernate Struts Training how to retrieve text and images from mysql database and show on html page using jsp servlet How to install Neo4j on Ubuntu 15.10? please help me in these prog MYSQL - mysql copy table to another table example by creating new table solution for mapping hibernate and pojos from net beans through database Connect GWT application with Oracle inventory System of Medical Store inventory System of Medical Store inventory System of Medical Store inventory System of Medical Store This code have created jTable that connected with a database.every cell of last column have a button.But this button doesn't work properly.Where is the error java program Java Database Program jdbc Database connection class in a live project ..?? What is JDBC architecture? Unable to Create DSN for excel to ms access importing data and edit that data Database Scrolling Buttons how to use foreign key in java How to delete content of a log file from linux terminal? JSP-Oracle connectivity Student Management System Java code for Saving Marathi (Indian local language ) in Mysql and retrieving the same crud operations with foreign key constraint. I really need help with this assignment question Please help me out Please Backup Failed Mysqldump Got Errno 28 On Write Upgrade MySQL 5.1 to 5.5 in cpanel mysqldump all databases com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'jpa.sequence' doesn't exist persistence xml class element persistence.xml for MySQL MySQL JDBC Driver pom dependency code Blob column jdk6 and oracle 8i connexion oracle 8i et jdk6 java [ cannot retrive date from sql ] why?? Order Entry System How to threow timeout exception when DB is not responding How to threow timeout exception when DB is not responding This is the employee form to add data to mysql database but I got error of NullPointerException, Is this write code please give me feedback as soon as possible make a method which takes user name & pwd as parameter & validate them against the database. If the corresponding user exist return true otherwise false. prabhakar validating credentials and displaying error message in login .jsp if not valid JDBC jdbc jdbc code register servlet vibhu connectiondetails from vibhu

Ads

 
Advertisement null

Ads