开发者

Insert values into an Access Database that contain brackets/braces

开发者 https://www.devze.com 2023-04-05 10:12 出处:网络
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

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;
开发者_JAVA百科
            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?


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...

0

精彩评论

暂无评论...
验证码 换一张
取 消