Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,

I am completing my project. That is last corner. But During the day(8 hours) I couldnt step a step. Please help me. I will explain clearly.

I want to add instructors into my database which is an jdbc. I created database it is working there is no problem with connection.

An instructor will have this information.
*Name
*Surname
*Title
*İmage (This is so important)

I have created Jpanel in netbeans.

http://www.imagetoo.com/images/untitlqfq.png[^]

As you can see in this picture, I cant put a picturebox or whatever it is. I want something like filechooser.

Namely my first problem is this.

Second problem is how to create a table with image. Namely I have used varchar or integers. Based on my research I have seen blob? but I didint understand I am making my image column type as blob but errors.
Last problem is with 'ID' column. I am taking an error similar ID column can not be assigned to a null value.

And here is my database view.

http://www.imagetoo.com/images/untitlkhk.png[^]

ID > Integer
Image > BLOB
Others >Varchar

If someone helps me I will be very very happy. This is very important for me. I am adding my java code.
SAVE BUTTON CODE
Java
try {
           //1.Kısım Baglantı Saglıyoruz
           this.host = "jdbc:derby://localhost:1527/EMRE";
           this.Name = "emre";
           this.Pass = "2561";
           Connection con = DriverManager.getConnection(host,Name,Pass);

           //2.Kısım Statement Olusturuyorum

           Statement cumle = con.createStatement();


           cumle.executeUpdate("INSERT INTO INSTRUCTOR " + " (INAME, ISURNAME, ITITLE,ID)" + " VALUES ('"+txtInstName.getText()+"','"+txtInstSurname.getText()+"','"+cmbInstTitle.getSelectedItem()+"')");
           JOptionPane.showMessageDialog(null, cmbInstTitle.getSelectedItem()+txtInstName.getText()+ " " + txtInstSurname.getText()+"Has Been Added");
           }
       catch (SQLException ex) {
           JOptionPane.showMessageDialog(null, ex);
       }
   }



EDIT: A DESKTOP APPLICATION




IMPROVEMENT
**********************************************************************************
Hello again,

I have found something on the web modified with(really difficult for me :))

Under the save button

Java
try {
          //1.Kısım Baglantı Saglıyoruz
          this.host = "jdbc:derby://localhost:1527/EMRE";
          this.Name = "emre";
          this.Pass = "2561";
          Connection con = DriverManager.getConnection(host,Name,Pass);

          //2.Kısım Statement Olusturuyorum

          Statement cumle = con.createStatement();
          ResultSet rs = null;
          PreparedStatement psmnt = null;
          FileInputStream fis;
          Class.forName("org.apache.derby.jdbc.ClientDriver");
          /* Create a connection by using getConnection() method that takes parameters of string type connection url, user name and password to connect to database. */

          // create a file object for image by specifying full path of image as parameter.
          File image = new File("C:\\Documents and Settings\\temre\\Desktop\\IMAGE\\image.jpg");/* prepareStatement() is used for create statement object that is used for sending sql statements to the specified database. */
          psmnt = con.prepareStatement("insert into INSTRUCTOR(INAME, ISURNAME, IMAGE, ITITLE) "+ "values(DEFAULT)");
          psmnt.setString(1,"EMRE");
          psmnt.setString(2,"emre");
          psmnt.setString(4,"2561");
          fis = new FileInputStream(image);
          psmnt.setBinaryStream(3, (InputStream)fis, (int)(image.length()));/* executeUpdate() method execute specified sql query. Here this query insert data and image from specified address. */
          int s = psmnt.executeUpdate();
          if(s>0)
          {JOptionPane.showMessageDialog(null,"Uploaded successfully !");}
          else
          {JOptionPane.showMessageDialog(null," nooo :( !");}
         }

   catch (Exception ex)  {JOptionPane.showMessageDialog(null,"ERROR !"+ex);}


I am taking an error such as "the number of values assigned is not the same as the number of specified or implied columns" This is why because I don't have a box to upload image.

Please give me hand. And one more, I didint understand defining a path inside code ? Why do I need such a path? Where the images go?
Posted
Updated 14-Aug-12 21:47pm
v3

To upload an image using Java (or any programming language, for that matter), you basically have two options:
- Upload the picture as a blob (what you're trying to do, BUT, you need to turn the picture into a stream -> see example here[^] for instance), or:
- Upload the picture to your server, retrieve its path and store that path into your database.

Now, both approaches have advantages and disadvantages (see here[^] for a more in-depth discussion)

In most of the projects I've worked on (including my current one) we've gone with uploading the pictures to the server and storing the path into the database. It tends to be much, much faster when you're dealing with lots of users that retrieve an average of 10-15 pictures per request. It also comes more naturally to the webserver to deliver a file at a path, versus you retrieving the blob from the database, recomposing it as a file, and returning it to the user.

Although you said it's for a school project, I'd advise you to go with the option of storing them on the server and saving their paths in the database. You can find some examples here[^] and here[^]
 
Share this answer
 
Comments
FoxRoot 15-Aug-12 2:01am    
Thanks Andrei very informative solution but this is an desktop application. I couldn't understand the examples. Do I need a picturebox, a filechooser? and where should I start ?
Andrei Straut 15-Aug-12 5:13am    
I have posted some explanations below. Also, being a desktop application, you would need a jFileChooser, set it's default target directory with a relative path (see below) and then upload it
I'm posting this as a solution, and not as a comment, because i think it is a larger explanation, and not a comment in itself

This line:
psmnt = con.prepareStatement("insert into INSTRUCTOR(INAME, ISURNAME, IMAGE, ITITLE) "+ "values(DEFAULT)");


PreparedStatements don't work that way. You need to bind the same number of parameters as specified by the columns in the insert statement. (Even if they are default values for the column, which is what the DEFAULT key word is).

In your specific case, the insert statement would be:
psmnt = con.prepareStatement("insert into INSTRUCTOR(INAME, ISURNAME, IMAGE, ITITLE) "+ "values(DEFAULT, DEFAULT, DEFAULT, DEFAULT)");

You need to have the same number of placeholder values (default) as the number of columns specified. This is why it's throwing you an error.

As for defining a path inside your code, let's start here:
File image = new File("C:\\Documents and Settings\\temre\\Desktop\\IMAGE\\image.jpg");

So, you have defined a path to where is picture is. BUT, what if someone else (I, for instance) get the application and want to run it? I don't have that path in my computer and defining it would be a hassle, and the closest corresponding path (for my computer) would be
File image = new File("C:\\Users\\Andrei-PC\\Desktop\\IMAGE\\image.jpg");


Defining a path means specifying a default file/folder path, which is likely to work on most computers, on most operating systems, be it Linux, Mac, or Windows.

You have an API in Java to do that, and you can start with the System Properties API. For instance, you can issue this, and it will work under both Linux and Windows (haven't tested it with MAC):
System.getProperty("user.home")

Under Windows, this will return C:\\Users\\Andrei-PC\\, while under Linux it will return /home/Andrei-PC/

Now, having that path, you can start from there, and create a folder where to store your files.

Good luck!
 
Share this answer
 
Comments
FoxRoot 15-Aug-12 5:37am    
Thank you so much Andrei. But stil have problems I cant handle :(
Andrei Straut 15-Aug-12 5:39am    
Like?
FoxRoot 15-Aug-12 5:46am    
Firstly, I cant put a browse button to seach around computer(Filechoser) covers all my panel. and second that is my first database-image event. It comes difficult. I am trying more than 3 days. Actually that is so simple I want to add a name a surname and an image. This must not be so difficult. See this time I am taking another error. "The column position '1' is out of range. The number of columns for this ResultSet is 0". Andrei there is no picture box or filechoser on my form. You can check the link in my question. That really depressed me. I should do that.
FoxRoot 15-Aug-12 5:46am    
Sorry I forgot. Thank you for your consideration.
About the fileChooser - You don't display it directly, that's bad practice. You need a "Browse" button, and when your user presses that button, the you display the fileChooser in a modal window. Check below (working example, tested on my computer).

First, declare and instantiate your file chooser:
Java
javax.swing.JFileChooser jFileChooser1 = new javax.swing.JFileChooser();
jFileChooser1.setDialogTitle("Choose file....");



Then, create a button to serve as your browse button (also add actionListener to it, so the button knows what to do when clicked):
javax.swing.JButton jButton1 = new javax.swing.JButton();
jButton1.setText("Browse");
jButton1.addActionListener(new java.awt.event.ActionListener() {
   public void actionPerformed(java.awt.event.ActionEvent evt) {
      jButton1ActionPerformed(evt);
  }
});


And finally, define what actually happens when the button is clicked:
Java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    int returnValue = jFileChooser1.showOpenDialog(this);
    jFileChooser1.setVisible(true);
    
    if (returnValue == JFileChooser.APPROVE_OPTION) {
        File file = jFileChooser1.getSelectedFile();
        //Now you have the file, serialize it and upload it to database
    } else {
        //Do what you want to do when user doesn't upload anything
    }
}


Also, I have no idea how soon I will be able to respond if you have any further problems, as I need to go and take care of some issues.
I do hope another member can come along and help you. You can also post a link to this question in the programming forums, in the Java section (DO NOT POST A FULL QUESTION!). Say what you've tried, you still need help, and link it to this question, maybe someone else will take a look at it.

TuranEmre wrote:
Sorry I forgot. Thank you for your consideration.


No problem. If by what I did here I helped someone understand how something works and maybe solve a problem, it's all ok. CodeProject has helped me when I needed it, so I'm just giving that back
 
Share this answer
 
v3
Comments
FoxRoot 15-Aug-12 6:31am    
Thank you thank you so much :) Now I can open filechoser. When I saw that filechoser panel a stupid smile sit on my face :) But stil can not upload to database. So I will do what you suggest. I will post to forums just the link :)
Thanks Andrei, have nice day.
FoxRoot 15-Aug-12 10:30am    
Still couldnt solve the error. I am takng the same error message. I started not believing to add an image into database is not possible :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900