Insert values into an Access Database that contain

2019-09-16 12:35发布

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?

1条回答
太酷不给撩
2楼-- · 2019-09-16 13:19

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

查看更多
登录 后发表回答