Question

Using taglib-sharp and OleDb, I'm attempting to index a folder of music files and store all the metadata from said files in an Access Database (I'll probably switch to SQL Compact or something later but the book I have uses Access). The below code should retrieve and store the metadata of the first 1000 files in a given folder and subfolders

OleDbCommand cmd = con.CreateCommand();
DirSearch(@"C:\Users\Stephen\Music");
TagLib.File tagFil;

for (int i = 0; i < 1000; i++)
        {
            tagFil = TagLib.File.Create(filesFound[i]);
            string album = tagFil.Tag.Album;
            string artist = tagFil.Tag.FirstPerformer;
            string title = tagFil.Tag.Title;

            if (album == null)
                album = "Unknown Album";
            if (artist == null)
                artist = "Unknown Artist";
            if (title == null)
                title = "Unknown Track";
            cmd.CommandText = "INSERT INTO Track (Title,Artist,Album,Path) VALUES ('" + title + "','" + artist + "','" + album + "','" + filesFound[i] + "')";
            cmd.ExecuteNonQuery();
        }

The problem, however, occurs when one of the tags has a bracket in the title. I can see why this would cause a problem but not how to solve/avoid it. I have tried string literals etc but couldn't see how they would work (they don't :/). Any better ideas?

Was it helpful?

Solution

You should use parameterized queries to accomplish this .

Untested code:

cmd.CommandText = "INSERT INTO Track (Title,Artist,Album,Path) VALUES (?, ?, ?, ?)";
cmd.Parameters.Add(title);
cmd.Parameters.Add(artist);
cmd.Parameters.Add(album);
cmd.Parameters.Add(filesFound[i]);

Links:
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters.aspx

Your code, as is, is ripe for SQL injections...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top