Databases and Java

I am almost finished with this program, but I am getting a strange error. Here is the assignment description: http://condor.depaul.edu/~jpetlick/extra/212/A07_212.html I would greatly appreciate any help. Thank you! (I know I eventually need to output this to files, but I currently left that out for debugging purposes.)
-------------Error Message------------------------
The balance of accounts prior to money transfers is:
Account Balance
1 $10,000.00
2 $10,000.00
3 $10,000.00
4 $10,000.00
5 $10,000.00
6 $10,000.00
7 $10,000.00
8 $10,000.00
9 $10,000.00
10 $10,000.00
Total $100,000.00
TranID From Balance to Balance
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.
-------------------Code----------------------
import java.sql.*;
import java.util.*;
import java.io.*;
import java.text.NumberFormat;
public class Transfer
public static void main(String[] args)
throws ClassNotFoundException, SQLException, IOException
String file = "Report.dat", file2 = "Log.dat", sql = "";
int sum = 0, trans = 1, accountWithdraw = 0, accountDeposit = 0, total = 0;
int randomAcctWithdraw = 0, randomAcctDepo = 0;
//-----Load database driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//-----File Writers
FileWriter fw = new FileWriter (file);
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter outFile = new PrintWriter (bw);
FileWriter fw2 = new FileWriter (file2);
BufferedWriter bw2 = new BufferedWriter (fw2);
PrintWriter outFile2 = new PrintWriter (bw2);
NumberFormat money = NumberFormat.getCurrencyInstance();
try
//-----Create Database Connection object.
Connection c = DriverManager.getConnection("jdbc:odbc:Banking");
//-----Create Statement object.
Statement s = c.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
s.execute("CREATE TABLE MyBank " + "(AccountNum Number, Balance Number)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('1', 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('2', 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('3', 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('4', 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('5', 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('6', 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('7', 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('8', 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('9', 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "('10', 10000)");
String selection = "SELECT AccountNum, Balance FROM MyBank";
ResultSet r = s.executeQuery(selection);
System.out.println ("The balance of accounts prior to money transfers is:");
System.out.println ("\tAccount\t Balance");
while(r.next())
System.out.println("\t" + r.getInt(1) + "\t" + money.format(r.getInt(2)));
sum += r.getInt(2);
System.out.println("\tTotal\t" + money.format(sum));
System.out.println ("\nTranID\tFrom\tBalance\tto\tBalance");
r = s.executeQuery(selection);
r.first();
for (int i=0; i <= 1000; i++)
accountWithdraw = (int) ((Math.random() * 10) + 1);
accountDeposit = (int) ((Math.random() * 10) + 1);
r.first();
while(r.next())
while ( (accountWithdraw == r.getInt(1)) || (accountWithdraw == accountDeposit) )
accountWithdraw = (int) ((Math.random() * 10) + 1);
accountDeposit = (int) ((Math.random() * 10) + 1);
r.absolute(accountWithdraw);
s.executeUpdate("UPDATE MyBank SET Balance = " + (r.getInt(2) - 1000) + " WHERE AccountNum = " + accountWithdraw);
r = s.executeQuery(selection);
r.absolute(accountDeposit);
s.executeUpdate("UPDATE MyBank SET Balance = " + (r.getInt(2) + 1000) + " WHERE AccountNumber = " + accountDeposit);
System.out.print (trans + "\t" + accountWithdraw + "\t" + s.executeQuery("SELECT Balance FROM MyBank WHERE AccountNum = " + accountWithdraw) + "\t" + accountDeposit + "\t" + s.executeQuery("SELECT Balance FROM MyBank WHERE AccountNum = " + accountDeposit));
r.first();
trans++;
r.first();
System.out.println ("\nThe balance of accounts after money transfers is:");
System.out.println ("\tAccount\t Balance");
while (r.next())
System.out.println("\t" + r.getInt(1) + "\t" + money.format(r.getInt(2)));
total += r.getInt(2);
System.out.println ("\tTotal: " + money.format(total));
//-----Close Connections
c.close();
catch(SQLException err)
System.out.println (err);

Well I changed some thing and it seems as if I'm so close but I keep getting this error. The wierd thing is it doesn't always break there. Sometimes it breaks at 14 transactions, sometimes 85, all kinds of numbers. I can't figure that out. Thanks for all the help, i appreciate it.
The balance of accounts prior to money transfers is:
Account Balance
1 $10,000.00
2 $10,000.00
3 $10,000.00
4 $10,000.00
5 $10,000.00
6 $10,000.00
7 $10,000.00
8 $10,000.00
9 $10,000.00
10 $10,000.00
Total $100,000.00
TranID From Balance to Balance
1 8 9000 6 11000
2 3 9000 9 11000
3 7 9000 8 10000
4 10 9000 9 12000
5 1 9000 9 13000
6 4 9000 8 11000
7 8 10000 6 12000
8 5 9000 9 14000
9 7 8000 2 11000
10 3 8000 9 15000
11 9 14000 2 12000
12 8 9000 10 10000
13 4 8000 3 9000
14 8 8000 10 11000
15 3 8000 2 13000
16 10 10000 9 15000
17 5 8000 7 9000
18 9 14000 1 10000
19 3 7000 5 9000
20 9 13000 3 8000
21 3 7000 8 9000
22 8 8000 6 13000
23 7 8000 2 14000
24 3 6000 4 9000
25 1 9000 5 10000
26 8 7000 1 10000
27 4 8000 5 11000
java.sql.SQLException: No data found
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:6287)
at sun.jdbc.odbc.JdbcOdbc.SQLGetDataInteger(JdbcOdbc.java:3211)
at sun.jdbc.odbc.JdbcOdbcResultSet.getDataInteger(JdbcOdbcResultSet.java:5434)
at sun.jdbc.odbc.JdbcOdbcResultSet.getInt(JdbcOdbcResultSet.java:571)
at Transfer.main(Transfer.java:76)
My altered code:
import java.sql.*;
import java.util.*;
import java.io.*;
import java.text.NumberFormat;
public class Transfer
public static void main(String[] args)
throws ClassNotFoundException, SQLException, IOException
String file = "Report.dat", file2 = "Log.dat", sql = "";
int sum = 0, trans = 1, accountWithdraw = 0, accountDeposit = 0, total = 0;
//-----Load database driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//-----File Writers
FileWriter fw = new FileWriter (file);
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter outFile = new PrintWriter (bw);
FileWriter fw2 = new FileWriter (file2);
BufferedWriter bw2 = new BufferedWriter (fw2);
PrintWriter outFile2 = new PrintWriter (bw2);
NumberFormat money = NumberFormat.getCurrencyInstance();
try
//-----Create Database Connection object.
Connection c = DriverManager.getConnection("jdbc:odbc:Banking");
//-----Create Statement object.
Statement s = c.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
s.execute("CREATE TABLE MyBank " + "(AccountNum Number, Balance Number)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(1, 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(2, 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(3, 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(4, 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(5, 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(6, 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(7, 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(8, 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(9, 10000)");
s.executeUpdate("INSERT INTO MyBank VALUES " + "(10, 10000)");
String selection = "SELECT AccountNum, Balance FROM MyBank";
ResultSet r = s.executeQuery(selection);
System.out.println ("The balance of accounts prior to money transfers is:");
System.out.println ("\tAccount\t Balance");
while(r.next())
System.out.println("\t" + r.getInt(1) + "\t" + money.format(r.getInt(2)));
sum += r.getInt(2);
System.out.println("\tTotal\t" + money.format(sum));
System.out.println ("\nTranID\tFrom\tBalance\tto\tBalance");
r = s.executeQuery(selection);
r.first();
for (int i=0; i <= 1000; i++)
r.first();
while(r.next())
accountWithdraw = (int) ((Math.random() * 10) + 1);
accountDeposit = (int) ((Math.random() * 10) + 1);
while ( (accountWithdraw == r.getInt(1)) || (accountWithdraw == accountDeposit) )
accountWithdraw = (int) ((Math.random() * 10) + 1);
accountDeposit = (int) ((Math.random() * 10) + 1);
r.absolute(accountWithdraw);
s.executeUpdate("UPDATE MyBank SET Balance = " + (r.getInt(2) - 1000) + " WHERE AccountNum = " + accountWithdraw);
r = s.executeQuery(selection);
r.absolute(accountWithdraw);
System.out.print (trans + "\t" + accountWithdraw + "\t" + r.getInt(2) + "\t" + accountDeposit + "\t");
r.absolute(accountDeposit);
s.executeUpdate("UPDATE MyBank SET Balance = " + (r.getInt(2) + 1000) + " WHERE AccountNum = " + accountDeposit);
r = s.executeQuery(selection);
r.absolute(accountDeposit);
System.out.println (r.getInt(2));
r.first();
trans++;
r.first();
System.out.println ("\nThe balance of accounts after money transfers is:");
System.out.println ("\tAccount\t Balance");
while (r.next())
System.out.println("\t" + r.getInt(1) + "\t" + money.format(r.getInt(2)));
total += r.getInt(2);
System.out.println ("\tTotal: " + money.format(total));
//-----Close Connections
c.close();
catch(SQLException err)
err.printStackTrace(System.out);
}

Similar Messages

  • Database and java class

    Is there a tool that automatic create a java class related to a database? Similar dataset in .NET?

    create a database? nyet.
    There are relational databases written in Java and there are tools in java with which one can access a DBMS.
    Either use a search engine, look at the java.sql and javax.sql packages, or post more information.

  • JDO database and Java Swing

    Was just wundering if it is possible to query a java jdo database with a swing frontend, and if so if anybody can direct me to any helpful websites.
    Cheers

    Sure it is possible.
    Do you know JDO? Googling for "JDO tutorial" should get you well on your way. Ditto for Swing / Swing tutorial.
    Keep the database stuff and the GUI stuff in separate classes. That way you can write quickie command line main() functions to test a database method. Or, as you advance, you may want to learn about jUnit (->google).
    There are application architecture issues that are mucho difficult to guess at without more details. Such as if your application is pretty big, you might want to look into some sort of client/server distributed architecture. But for simpler stuff, a single application should be a fine way to start.

  • Question about database and java

    Suppose i have a form with a bunch of textboxes etc.
    What is the best way to send the data from the
    result set to the form objects.
    Thanks in advance
    Maggie

    hi,
    first you use the array of buttons then in a loop
    you should adopt the logic
    for(i=0;i<=10;i++)
    myButton.setTrxt(RecordSet[i]);
    where condition depends on the no of buttons.
    zafir

  • How Connect to oracle database with java

    i have trouble with my program
    i use oracle 8i to my database and java for interface
    this mycode :
    import java.sql.*;
    class TestThinApp {
    public static void main (String args[])
    throws ClassNotFoundException, SQLException {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    // or you can use:
    // DriverManager.registerDriver(
    // new oracle.jdbc.driver.OracleDriver());
    Connection conn = DriverManager.getConnection(
    "jdbc:oracle:thin:@dssw2k01:1521:orcl","scott","tiger");
    Statement stmt = conn.createStatement();
    ResultSet rset = stmt.executeQuery(
    "select 'Hello Thin driver tester '||USER||'!' result from dual");
    while(rset.next())
    System.out.println(rset.getString(1));
    rset.close();
    stmt.close();
    conn.close();
    i have trouble , becouse i can connect my database with java (JDK)
    if any one can help me pls?
    arif

    PLEASE .... Ask in an Oracle Java forum.
    And read the documentaiton. There is a whole document devoted to doing that. http://download.oracle.com/docs/cd/B19306_01/java.102/b14355/toc.htm has examples.
    PLEASE ... do not ask product questions in a forum which clearly has a title saying it is devoted to assisting with download problems.

  • I m using ms access as database and i want to create a login page in java

    hye frnz... plz help me m new to java
    m using ms access as database and try to create a login page where user type username and pw
    i had enter valid user entries in database i checked connectivity is working i want as user login the main window must open after checking username and pw field to database but
    now there is an error class not found exception sun:jdbc...... error
    plz help me i had stuck frm 4 days */
    import java.sql.DriverManager;
    import java.sql.Connection;
    import java.sql.Statement;
    import java.sql.ResultSet;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Login extends JFrame
    //Component Declarations
    JLabel jlb1,jlb2;
         JTextField jtf1;
         JPasswordField jpf1;
         JButton jb1,jb2;
         //Constructor
         Login()
         //frame settings
              setTitle("Login Dialog");
              setLayout(new GridBagLayout());
              GridBagConstraints gbc = new GridBagConstraints();
              setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              Dimension d= Toolkit.getDefaultToolkit().getScreenSize();
              setBounds(d.width/2-175,d.height/2-100,350,200);
              gbc.insets=new Insets(7,7,7,7);
         //adding components
              jlb1=new JLabel("User ID");
              gbc.gridx=0;
              gbc.gridy=0;
              add(jlb1,gbc);
              jlb2=new JLabel("Password");
              gbc.gridx=0;
              gbc.gridy=1;
              add(jlb2,gbc);
              jtf1=new JTextField(10);
              gbc.gridx=1;
              gbc.gridy=0;
              add(jtf1,gbc);
              jpf1=new JPasswordField(10);
              gbc.gridx=1;
              gbc.gridy=1;
              add(jpf1,gbc);
              jb1=new JButton("Login");
              gbc.gridx=0;
              gbc.gridy=2;
              add(jb1,gbc);
              jb1.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae)
                   Connection conn=null;
                        Statement stmt=null;
                        boolean found=false;
                   try
                             Class.forName("sun.jdbc.driver.JdbcOdbcDriver");
                             String dataSourceName = "Inventory";
                             String dbURL = "jdbc:odbc:" + dataSourceName;
                             conn=DriverManager.getConnection(dbURL, "","");
                             stmt=conn.createStatement();
                             ResultSet rst=stmt.executeQuery("Select * from User");
                             System.out.println(jtf1.getText()+"/t"+jpf1.getPassword());
                             while(rst.next())
                                  System.out.println( rst.getString(1) +"/t"+ rst.getString(2));
              if(jtf1.getText().equals(rst.getString(1).trim()) && new String(jpf1.getPassword()).equals(rst.getString(2).trim()))
                                       found=true;
                                       rst.close();
                                       dispose();
                                       MainWindow mw= new MainWindow();     /*created min window object created to be opend after login but not working*/     
                                       break;
                             rst.close();
                             stmt.close();
                             conn.close();                    
                        catch(ClassNotFoundException e){System.out.print(e);}
                        catch(Exception e){System.out.print(e);}
                        if(found==false) /*this portion is executing and dialog box appears invalid name and pw with class not found exception sun:jdbc.......on console */
                             JOptionPane.showMessageDialog(null,"Invalid username or password",
                                  "Error Message",JOptionPane.ERROR_MESSAGE);
              jb2=new JButton("Clear");
              gbc.gridx=1;
              gbc.gridy=2;
              add(jb2,gbc);
              jb2.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae)
                        jtf1.setText("");
                        jpf1.setText("");
                        jtf1.requestFocus();
              setSize(350,200);
              setVisible(true);
              jtf1.requestFocus();
         public static void main(String args[])
    Login l=new Login();
    }

    http://forums.oracle.com/forums/ann.jspa?annID=599
    Oh, and by the way, your keyboard seems to be broken as your words are not getting spelled correctly.

  • How create new database and table in java db and how get java db backup

    hi master
    sir i use stuido creator
    sir please give me idea how i create new database
    and how create new table and view in this new database
    and how get this database backup
    how i give this databae backup to isp for deployment
    please give me idea with step
    thank
    aamir

    Create your own Value Object (Data Transfer Object) in Java with a structure similar to this and map the fields returned from the database to the fields of that object (preferably using SEtT methods).
    Hope this helps.

  • Connect to database and write query statements in the *****Impl.java??

    http://www.oracle.com/technology/pub/articles/vohra-jdev-xmlpub.html
    I used the above link to create XML's and from there a formatted report of data from the database. I accomplish this by connecting to the database inside the XMLPublisher.java file. I also have my query hard-coded inside the DataTemplate.xml to extract the info from the database. This limits my ability on what the user can accomplish with the system.
    Is it possible to run my reports based on an iterator within Jdeveloper, as opposed to having to manually enter the query and connect to the database within the XMLPublisher.java file and the template.xml? ..Possibly connecting to the database and and writing queries in the *****impl.java?
    Thanks.

    Rather than inventing your own demi-donkeyed solution I recommend you consider using Oracle's Fine-Grained Auditing which does precisely this.
    Cheers, APC

  • High performance in memory database supporting C++ and JAVA

    Hi,
    I am considering to build a Java compatible In memory database to speed up the application of JAVA. We have now the C++ version of the database, named MTDB, which is hundreds of times faster than phisical database. The in memory database runs on solaris, linux and windows system. MTDB supports load sharing, data distribution, and realtime data synchronizing. MTDB shows large capacity, great performance, stability, and scalability in telecom applications. Add JAVA access interface to MTDB is very valuable. Please send me email if you have interest in this.
    Thanks.

    Are you selling it? In which case advertisements are not appropriate here.
    There are a bunch of existing in-memory databases for Java which offer significant performance enhancements - unless yours outdoes them considerably I think you'll find a very limited market.
    Check out hsqldb.org for one example.

  • What is the diffrence between package javax.sql and java.sql

    Is javax designed for J2EE?
    And when to use package javax?

    Hi,
    What is the diffrence between package javax.sql and java.sql?The JDBC 2.0 & above API is comprised of two packages:
    1.The java.sql package and
    2.The javax.sql package.
    java.sql provides features mostly related to client
    side database functionalities where as the javax.sql
    package, which adds server-side capabilities.
    You automatically get both packages when you download the JavaTM 2 Platform, Standard Edition, Version 1.4 (J2SETM) or the JavaTM 2, Platform Enterprise Edition, Version 1.3 (J2EETM).
    For further information on this please visit our website at http://java.sun.com/j2se/1.3/docs/guide/jdbc/index.html
    Hope this helps.
    Good Luck.
    Gayam.Srinivasa Reddy
    Developer Technical Support
    Sun Micro Systems
    http://www.sun.com/developers/support/

  • PL/SQL and Java implementation

    Hi all,
    We need to implement a fast solution for reporting to our existing web application. Application is totally based on stored procedures written in PL/SQL.
    We have already java classes for drawing different types of charts
    named Chartdirector (http://www.advsofteng.com/)
    This library can create chart images in memory.
    I have already read about calling java classes from PL/SQL and SQLJ too.
    My questions are;
    1. Is this safe to include classes to database and create
    reports by using loadjava in real life. I mean not in theory, in real life?
    2. Is there any experiments of the audience about this method?
    3. Would it be any performance problems about this?
    4. Should i prefer to use any Java container and jsps instead of this method?
    I will continue to research for necessary steps after i could see the light :)
    Thank you to all,
    Regards,
    Gokhan

    > 1. Is this safe to include classes to database and create
    reports by using loadjava in real life. I mean not in theory, in real life?
    Yes.
    > 2. Is there any experiments of the audience about this method?
    Experiments and actual implementation - yes. It works. Granted, it does not always work as easy as running the Java code from the command line. But it does work.
    > 3. Would it be any performance problems about this?
    This is a potential problem with any software code.
    4. Should i prefer to use any Java container and jsps instead of this method?
    To be honest, I prefer not using Java for web graphics as I'm not impressed with the quality and flexibility of the graphs generated. I prefer using (and paying for commercial use) for the JPGraph classes for PHP - and using that from PL/SQL (via Zend Core for Oracle).
    Another option is to use SVG and generated SVG directly from PL/SQL. But this requires a browser plugin and SVG also does not look that great. (this is btw what Oracle's HTMLDB does and uses)

  • Getting specific values From a database in Java

    Hey,
    I'm using XE and building an application in Java to do basic CRUD operations on the database.
    One of these operations is searching for a customer by last name (which runs fine) and the result of the query (a customer ID, a first name, and a last name) is displayed in a JTable. I want to be able to click on the record I need and use the customer ID to do an insert on another table CUSTOMER_PURCHASES which maps purchases to customers.
    How do I go about doing this knowing that customer ID is an auto-incremented number (using a SEQUENCE)?
    I thought about creating a variable in Java of type String called customerID and initialize it like this: String customerID = "CUSTOMER_SEQUENCE.nextval"
    But by doing this, I suspect that I'll be getting the next available customerID, not the one from the record I selected.
    Can anybody suggest a workaround or lead me in the right direction?
    Thank you in advance for the help and sorry about the long post, but I'm a newvbie to this field.

    As per raychen's advice, I was able to get the image from the database and bring it over into JavaFX.
    In my java class I retrieved the image as follows:
            BufferedImage image = null;  //Buffered image coming from database
            InputStream fis = null; //Inputstream
            try{
                ResultSet databaseResults;  //Returned results from DB
                stmt = conn.createStatement(); //Create the SQL statement
                databaseResults= stmt.executeQuery("SELECT * FROM mydb.`user` WHERE userID = 'username';"); //Execute query
                fis = blah.getBinaryStream(3);  //It happens that the 3rd column in my database is where the image is stored (a BLOB)
                image = javax.imageio.ImageIO.read(fis);  //create the BufferedImaged
            } catch (Exception e){
                     //print error if caught
           return image  //My function returns a BufferedImage objectSo in JavaFX, depending on how you have it set up, you essentially get the returned BufferedImage and create the image as follows:
    var bufferedImage : BufferedImage = theJavaFunctionThatReturnsABufferedImage();
    var newImage : Image = javafx.ext.swing.SwingUtils.toFXImage(bufferedImage);  //BufferedImageCheers and Happy New Year.

  • Problem with JSP and Java Servlet Web Application....

    Hi every body....
    I av developed a web based application with java (jsp and Java Servlets)....
    that was working fine on Lane and Local Host....
    But when i upload on internet with unix package my servlets and Java Beans are not working .....
    also not access database which i developed on My Sql....
    M using cpanel support on web server
    Plz gave me solution...
    Thanx looking forward Adnan

    You need to elaborate "not working" in developer's perspective instead of in user's perspective.

  • How to store file content in BLOB field MySql database using java

    Hi!
    i want to store the file content in a BLOB field in MySql database using java.
    Please help me out..........
    thanx in advance...
    bye

    i stored images in db, and retrieved them. like that cant i store pdf file in db, and retrieve it back using oracle db?
    Plz help me out how to put a file in db. i need complete code. thanks in advance.

  • How To Store pdf or doc file in Oracle Database using Java Jdbc?

    can any one help me out How To Store pdf or doc file in Oracle Database using Java Jdbc in JSP/Serlet? i tried like anything. using blob also i tried. but i am able 2 store images in DB not files. please if u know or else if u have some code like this plz send that to me, and help me out plz. i need that urgent.

    Hi.. i am not getting error, But i am not getting the original contents from my file. i am getting all ASCII vales, instead of my original data. here i am including my code.
    for Adding PDF in DB i used image.jsp
    Database table structure (table name. pictures )
    Name Null? Type
    ID NOT NULL NUMBER(11)
    IMAGE BLOB
    <%@ page language="java" import="java.util.*,java.sql.*,java.io.*" pageEncoding="ISO-8859-1"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <%
    try{
         Class.forName("oracle.jdbc.driver.OracleDriver");
         Connection con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.135:1521:orcl","scott","tiger");
         PreparedStatement ps,pstmt,psmnt;
         ps = con.prepareStatement("INSERT INTO pictures VALUES(?,?)");
    File file =
    new File("D:/info.pdf");
    FileInputStream fs = new FileInputStream(file);
    ps.setInt(1,4);
    ps.setBinaryStream(2,fs,fs.available());
    int i = ps.executeUpdate();
    if(i!=0){
    out.println("<h2>PDF inserted successfully");
    else{
    out.println("<h2>Problem in image insertion");
    catch(Exception e){
    out.println("<h2>Failed Due To "+e);
    %>
    O/P: PDF inserted successfully
    i tried to display that pdf using servlet. i am giving the code below.
    import java.io.IOException;
    import java.sql.*;
    import java.io.*;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class DispPDF extends HttpServlet {
         * The doGet method of the servlet. <br>
         * This method is called when a form has its tag value method equals to get.
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         public void service(HttpServletRequest request, HttpServletResponse response)
                   throws ServletException, IOException {
              //response.setContentType("text/html"); i commented. coz we cant use response two times.
              //PrintWriter out = response.getWriter();
              try{
                   InputStream sPdf;
                   Class.forName("oracle.jdbc.driver.OracleDriver");
                        Connection con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.135:1521:orcl","scott","tiger");
                        PreparedStatement ps,pstmt,psmnt;
                   psmnt = con.prepareStatement("SELECT image FROM pictures WHERE id = ?");
                        psmnt.setString(1, "4"); // here integer number '4' is image id from the table.
                   ResultSet rs = psmnt.executeQuery();
                        if(rs.next()) {
                   byte[] bytearray = new byte[1048576];
                        //out.println(bytearray);
                        int size=0;
                        sPdf = rs.getBinaryStream(1);
                        response.reset();
                        response.setContentType("application/pdf");
                        while((size=sPdf.read(bytearray))!= -1 ){
                        //out.println(size);
                        response.getOutputStream().write(bytearray,0,size);
                   catch(Exception e){
                   System.out.println("Failed Due To "+e);
                        //out.println("<h2>Failed Due To "+e);
              //out.close();
    OP
    PDF-1.4 %âãÏÓ 2 0 obj <>stream xœ+är á26S°00SIá2PÐ5´1ôÝ BÒ¸4Ü2‹ŠKüsSŠSŠS4C²€ê P”kø$V㙂GÒU×713CkW )(Ü endstream endobj 4 0 obj <>>>/MediaBox[0 0 595 842]>> endobj 1 0 obj <> endobj 3 0 obj <> endobj 5 0 obj <> endobj 6 0 obj <> endobj xref 0 7 0000000000 65535 f 0000000325 00000 n 0000000015 00000 n 0000000413 00000 n 0000000168 00000 n 0000000464 00000 n 0000000509 00000 n trailer <<01b2fa8b70ac262bfa939cc786f8770c>]/Root 5 0 R/Size 7/Info 6 0 R>> startxref 641 %%EOF
    plz help me out.

Maybe you are looking for

  • Errors when starting JMS Server

              When trying to start my managed server (after deployment) I get the following error:           Throwable: java.util.ConcurrentModificationException Exception raised: java.util.ConcurrentModificationException           java.util.ConcurrentMo

  • ORA-01401 with export/import

    Hi! I'm trying to migrate database from from version 8.0 on novell to 9.2 on Linux. I have precreated all tablespaces and all tables are succesfully created. In data import stage I got lot of "ORA-01401 inserted value too large for column" errors. An

  • HT1212 i need a new passcode . the computer that was use is out service and i dont know my passcode

    i need a new password on my ipod. my ipod was program by friends next door at xmas time.I am only 12 YEARS OLD now  and tha was 2 or 3 years ago. Can i change my password.

  • Java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

    Hi, I am using Jdeveloper 11.1.1.5. When we are trying to create a new row in the table through EO, we have overrided the default Create method in EOImpl. protected void create(AttributeList attributeList) { DBTransaction trans = getDBTransaction();

  • Can't run runInstaller

    I want to install Oracle 8.1.6 on Linux Redhat 6.2. I have created the oracle user, all the appropriate groups and the environment entries, following the installation reference from Oracle. Running ./runInstaller has no effect. The output is "Initial