Bild in einer Datenbank speichern?

Coder55

Mitglied
Hi leute,
Ich bin gerade mit einem Projekt beschäftigt. Und zwar ist mein Projekt ein Mp3 player in Java zu erstellen. Ich habe in dem Mp3 Player buttons Check Library,Update Library, Creat Playlist. So wenn ich auf Check Library gehe werden mir alle songs angezeigt.Durch eingeben des Track numbers wird mir der track gelistet.Dort steht dann wie viel mal dieser Track gespielt wurde und was für eine rating er bekommen hat.
Nun aber will ich zu diesem track ein Bild hinzufügen.Also wenn ich wieder den Track number eingebe soll dann wieder : Name des Tracks, diesmal Bild und dann noch wie viel mal er gespielt wurde.

Ich habe das mit dem Blob versucht jedoch bekomme ich hier auch Fehlermeldungen.
Mein Code
Code:
import java.sql.*; 
import java.io.ObjectOutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.swing.ImageIcon;

public class LibraryData {

    private static Connection connection;
    private static Statement stmt;

-----------------------------Das ist die Connection zur datenbank--------------------------------------------------
    static {
    
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            // Assumes Library.mdb is in the same folder as LibraryData.class
            String sourceURL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=Library.mdb;";
            connection = DriverManager.getConnection(sourceURL, "admin", "");
            stmt = connection.createStatement();
        } catch (Exception e) {
            // shouldn't happen if DB is set up correctly
            System.out.println(e);
        }
    }
------------------------------------------------------------------------------------------------------------------------------
    public static String listAll() {
        String output = "";
        try {
            // Need single quote marks ' around the key field in SQL. This is easy to get wrong!
            // For instance if key was "04" the SELECT statement would be:
            // SELECT * FROM LibraryTable WHERE key = '04'
            ResultSet res = stmt.executeQuery("SELECT * FROM LibraryTable");
            while (res.next()) { // there is a result
                // the name field is the second one in the ResultSet
                // Note that with  ResultSet we count the fields starting from 1
                output += res.getString(1) + " " + " - " + res.getString(4) + " (Played Time) " + res.getString(5) + " - " + res.getString(2) + " - " + res.getString(3) +  "\n";
            }
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
        return output;
    }

    public static String getName(String key) {
        try {
            // Need single quote marks ' around the key field in SQL. This is easy to get wrong!
            // For instance if key was "04" the SELECT statement would be:
            // SELECT * FROM LibraryTable WHERE key = '04'
            ResultSet res = stmt.executeQuery("SELECT * FROM LibraryTable WHERE key = '" + key + "'");
            if (res.next()) { // there is a result
                // the name field is the second one in the ResultSet
                // Note that with  ResultSet we count the fields starting from 1
                return res.getString(2);
            } else {
                return null;
            }
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }
-------------------------------------------------------------------- Das is der Part mit dem Blob---------------------------------------------------------------
	public static String getPicture(String key) {
       String sourceURL;
	   Connection con;
    con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=Library.mdb;");
       
    PreparedStatement ps;
// ich verstehe nicht ganz was ich in den Klammern hineinschreiben muss (name,Photo)+(value(?,?)
    ps = con.prepareStatement("insert into Pictrue(name,photo) " + "values(1,dj)");
    ps.setString(1, "dj");

    Blob blob = con.createBlob();
    ImageIcon ii = new ImageIcon("dj.gif");

    ObjectOutputStream oos;
    oos = new ObjectOutputStream(blob.setBinaryStream(1));
    oos.writeObject(ii);
    oos.close();
    ps.setBlob(2, blob);
    ps.execute();
    blob.free();
    ps.close();
    }
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
    public static String getArtist(String key) {
        // Similar to getName - use res.getString(3). If no result, return null
		try {
				// Need single quote marks ' around the key field in SQL. This is easy to get wrong!
				// For instance if key was "04" the SELECT statement would be:
				// SELECT * FROM LibraryTable WHERE key = '04'
				ResultSet res = stmt.executeQuery("SELECT * FROM LibraryTable WHERE key = '" + key + "'");
				if (res.next()) { // there is a result
					// the name field is the second one in the ResultSet
					// Note that with  ResultSet we count the fields starting from 1
					return res.getString(3);
				} else {
					return null;
				}
			} catch (Exception e) {
				System.out.println(e);
				return null;
			}
    }

    public static int getRating(String key) {
	
		// Similar to getName - use res.getInt(4). If no result, return -1
        //return -1;
	try {
				// Need single quote marks ' around the key field in SQL. This is easy to get wrong!
				// For instance if key was "04" the SELECT statement would be:
				// SELECT * FROM LibraryTable WHERE key = '04'
				ResultSet res = stmt.executeQuery("SELECT * FROM LibraryTable WHERE key = '" + key +"'" );
				if (res.next()) { // there is a result
					// the name field is the second one in the ResultSet
					// Note that with  ResultSet we count the fields starting from 1
					return res.getInt(4);
				} else {
					return -1;
				}
			} catch (Exception e) {
				System.out.println(e);
				return -1;
			}

    }

    public static int getPlayCount(String key) {
        // Similar to getName - use res.getInt(5). If no result, return -1
        //return -1;

try {
				// Need single quote marks ' around the key field in SQL. This is easy to get wrong!
				// For instance if key was "04" the SELECT statement would be:
				// SELECT * FROM LibraryTable WHERE key = '04'
				ResultSet res = stmt.executeQuery("SELECT * FROM LibraryTable WHERE key = '" + key + "'");
				if (res.next()) { // there is a result
					// the name field is the second one in the ResultSet
					// Note that with  ResultSet we count the fields starting from 1
					return res.getInt(5);
				} else {
					return +1;
				}
			} catch (Exception e) {
				System.out.println(e);
				return +1;
			}



    }

    public static void setRating(String key, int rating) {
        // SQL UPDATE statement required. For instance if rating is 5 and key is "04" then updateStr is
        // UPDATE Libary SET rating = 5 WHERE key = '04'
        String updateStr = ("UPDATE LibraryTable SET rating = " + rating + " WHERE key = '" + key + "'" );
        //System.out.println(updateStr);
        try {
            stmt.executeUpdate(updateStr);
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public static void incrementPlayCount(String key) {
		int playCount = getPlayCount(key) + 1;
       // SQL UPDATE statement required. For instance if rating is 5 and key is "04" then updateStr is
        // UPDATE Libary SET rating = 5 WHERE key = '04'
        String updateStr = "UPDATE LibraryTable SET playCount = " + playCount + " WHERE key = '" + key + "'";
        //System.out.println(updateStr);
        try {
            stmt.executeUpdate(updateStr);
        } catch (Exception e) {
            System.out.println(e);
        }
	
		// Similar to setRating - but must getPlayCount first and increment by 1
    }

    // close the database
    public static void close() {
        try {
            connection.close();
        } catch (Exception e) {
            // this shouldn't happen
            System.out.println(e);
        }
    }

    private String stars(int Rating) {
        String stars = "";
		// line 77-79 for loop assigning a control variable to a starting value
		// the test is carried out prior to any execution of the loop
		// it increments the control variable by 1
        for (int i = 0; i < Rating; ++i) {
            stars += "*";
        }
		// line 81 returns the value
        return stars;
    }
}



Meine Fehlermeldung:

Code:
---------- Javac ----------
LibraryData.java:77: cannot find symbol
symbol  : method getConnection(java.sql.Connection,java.lang.String)
location: class java.sql.DriverManager
	con = DriverManager.getConnection(con, "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=Library.mdb;");
	                   ^
1 error

Output completed (0 sec consumed) - Normal Termination
 
Zuletzt bearbeitet:
es gibt auch Java-Tags

---

an einer Stelle hast du
> String sourceURL = "jdbc😱dbc: Driver={Microsoft Access Driver (*.mdb)};DBQ=Library.mdb;";
> connection = DriverManager.getConnection(sourceURL, "admin", "");
was anscheinend hinhaut,

an anderer Stelle schreibst du anderen Code, wie die Fehlermeldung schon sagt stimmen die Parameter strukturell gar nicht
> con = DriverManager.getConnection(con, "jdbc😱dbc: Driver={Microsoft Access Driver (*.mdb)};DBQ=Library.mdb;");

diese Code-Zeile kommt im gepostenen Code-Block nicht vor, aber Java wird sie sich nicht ausgedacht haben,
auf jeden Fall hast du in getPicture() einen anderen Code,

sollte es nicht reichen, nur einmal eine Connection zu erstellen? du hast die sogar schon in einem static-Block,
das klingt doch ziemlich zentral global für alle, wieso überhaupt der zweite Aufruf?

------

getPicture() soll also ein Bild speichern? müsste die Methode dann nicht anders heißen?

> // ich verstehe nicht ganz was ich in den Klammern hineinschreiben muss (name,Photo)+(value(?,?)

PreparedStatement arbeitet mit Fragezeichen, richtig,
schau doch bitte in irgendein Tutorial, wie das grundsätzlich geht

Galileo Computing :: Java ist auch eine Insel (8. Auflage) – 23.10 Vorbereitete Anweisungen (Prepared Statements)

der Blob-Code danach sieht schon ziemlich fortgeschritten aus, vielleicht klappt es damit
 
Ich habe das gändern.Troztdem bekomme ich eine Fehlermeldung.
Mit getPicture will ich das bild in einem JTextarea anzeigen lassen,deswegen getPicture.



Code:
	public static String getPicture(String key) {
    String sourceURL;
    PreparedStatement ps;
	 ps = sourceURL.prepareStatement("insert into Pictrue(name,photo) " + "values(1,dj)");
     ps.setString(1, "dj");

    Blob blob = sourceURL.createBlob();
    ImageIcon ii = new ImageIcon("dj.gif");

    ObjectOutputStream oos;
    oos = new ObjectOutputStream(blob.setBinaryStream(1));
    oos.writeObject(ii);
    oos.close();
    ps.setBlob(2, blob);
    ps.execute();
    blob.free();
    ps.close();

    }

Fehlermeldung
Code:
---------- Javac ----------
LibraryData.java:78: cannot find symbol
symbol  : method prepareStatement(java.lang.String)
location: class java.lang.String
	 ps = sourceURL.prepareStatement("insert into Pictrue(name,photo) " + "values(1,dj)");
	               ^
LibraryData.java:81: cannot find symbol
symbol  : method createBlob()
location: class java.lang.String
    Blob blob = sourceURL.createBlob();
                         ^
2 errors

Output completed (0 sec consumed) - Normal Termination
 
hmm,

du rufst nun also die gewiss hochkomplexe Methode prepareStatement() an einer einfachen String-Variablen, nämlich sourceURL, auf?

wozu JDBC erfinden wenn man doch einfach
String x = "Hello World";
x.prepareStatement();
ausführen kann

nein so gehts nun nicht, prepareStatement() musst du schon an irgendwas JDBC-mäßigem aufrufen, nämlich der Connection,
wie du es vorher richtig hattest

ich schreibe das so deutlich weil das wirklich ein heftiger Fehler ist,
man kann doch nicht Befehle beliebig durcheinanderwerfen

die statische Variable connection muss deine Methode dominieren

-------

> Mit getPicture will ich das bild in einem JTextarea anzeigen lassen,deswegen getPicture.

willst du ein Bild aus der DB laden?
denn ansonsten kann ich 'bild in einem JTextarea anzeigen lassen' immer noch nicht mit dem Speichern eines Bildes in der DB in Verbindung bringen,
aber ist sicher weniger relevant
 
Zuletzt bearbeitet von einem Moderator:
Ich habe das jetzt so gemacht.Ich weis nicht ob das richtig ist, weil ich bin jetzt total verwirrt. Kann nicht mehr klar denken.
Sorry wenn ich dumme Fehler mache.Sitze schon seit heute morgen hier dran.

der neue Code

Code:
ResultSet res = stmt.executeQuery("Insert into Pictrue(name,photo) " + "values(1,dj)"+ key + "'");
	
    Blob blob = connection.createBlob();
    ImageIcon ii = new ImageIcon("dj.gif");

    ObjectOutputStream oos;
    oos = new ObjectOutputStream(blob.setBinaryStream(1));
    oos.writeObject(ii);
    oos.close();
    connection.setBlob(2, blob);
    connection.execute();
    blob.free();
    connection.close();


Fehlermeldung
Code:
---------- Javac ----------
LibraryData.java:86: cannot find symbol
symbol  : method setBlob(int,java.sql.Blob)
location: interface java.sql.Connection
    connection.setBlob(2, blob);
              ^
LibraryData.java:87: cannot find symbol
symbol  : method execute()
location: interface java.sql.Connection
    connection.execute();
              ^
2 errors

Output completed (0 sec consumed) - Normal Termination
 
tja, also ich spiele das Spiel nicht mit,
kannst ja einen Tag Pause machen,
und dann neu anfangen zu denken,

"wie kam ich jemals auf die Buchstabenkombination 'setBlob'? das muss ja die Methode irgendeiner Klasse sein,
wo habe ich das gelesen, wo kann ich das nachschauen? welche 5 Klassen habe ich überhaupt zur Auswahl"
usw.

setBlob und Connection passt schonmal nicht zusammen, das sagt dir die Fehlermeldung,
kannst dein alten Code anschauen oder gerne an allen verfügbaren Variablen ausprobieren, Anleitung, oder oder..
 
Zuletzt bearbeitet von einem Moderator:

Zurück
Oben