Insert values into an Access Database that contain brackets/braces

泪湿孤枕 提交于 2019-12-11 15:35:47

问题


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:


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



来源:https://stackoverflow.com/questions/7459360/insert-values-into-an-access-database-that-contain-brackets-braces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!