SQL UPDATE не обновляет базу данных, что-то не так с моим оператором SQL? - PullRequest
2 голосов
/ 22 апреля 2011

Это моя первая попытка «настоящей» программы на C #.Он берет указанный каталог, извлекает имя файла (без расширения) и записывает их в базу данных SQL.Эти данные затем считываются обратно в массив и передаются в цикл «foreach» ниже.Затем цикл использует данные для поиска в IMDB и сохраняет URL-адрес первого результата в БД.Затем он считывает эти данные обратно в переменную и использует их для «очистки» данных со страницы, таких как директор, приведение, сюжет и т. Д.

У меня есть программа, работающая вплоть до обновления базы данных в конце срежиссер, актерский состав, сюжет и др. данные.Я углубился в программу, и все переменные содержат правильные значения, просто когда форма загружает таблицу в DataGrid, она показывает все данные, которые я добавила ранее в цикле, но не директор и т. Д.

ДляПо этим причинам я думаю, что мой оператор SQL в конце программы может быть неверным.Я знаю, что код, вероятно, неэффективен и грязен, но я новичок во всем этом, так что будьте спокойны!

        foreach (string title in titles)
        {
            //Use each title in titles array to search IMDB and return the page URL
            string searchURL = "http://www.imdb.com/find?s=all&q=" + title;
            string url = searchURL;
            string sourceCode = WorkerClass.getSourceCode(url);
            int startIndex = sourceCode.IndexOf("Media from ");
            sourceCode = sourceCode.Substring(startIndex, sourceCode.Length - startIndex);
            startIndex = sourceCode.IndexOf("<a href=") + 9;
            int endIndex = sourceCode.IndexOf('"' + " onclick", startIndex);
            string link = "http://www.imdb.com" + (sourceCode.Substring(startIndex, endIndex - startIndex));

            //Update DB to add page url based on title
            SqlConnection con = new SqlConnection(DataAccess.GetConnectionString("dbCon"));
            //Create SQL Command
            var command = new SqlCommand("UPDATE movieTable SET imdbPageURL=@pageURL WHERE title=@title", con);
            command.Parameters.AddWithValue("@pageURL", link);
            command.Parameters.AddWithValue("@title", title);
            con.Open();
            //Add to DB
            command.ExecuteNonQuery();
            con.Close();

            //Select IMDB Page URL from movieTable where the title = current title
            var com = new SqlCommand("SELECT imdbPageURL FROM movieTable WHERE title=@title", con);
            con.Open();
            com.Parameters.AddWithValue("@title", title);
            string pageURL = (string)com.ExecuteScalar();
            con.Close();

            //Get Director
            sourceCode = WorkerClass.getSourceCode(pageURL);
            startIndex = sourceCode.IndexOf("description");
            sourceCode = sourceCode.Substring(startIndex, sourceCode.Length - startIndex);
            startIndex = sourceCode.IndexOf("content=") +21;
            endIndex = sourceCode.IndexOf('.' , startIndex);
            string director = sourceCode.Substring(startIndex, endIndex - startIndex);

            //Get Cast
            sourceCode = WorkerClass.getSourceCode(pageURL);
            startIndex = sourceCode.IndexOf("content=");
            sourceCode = sourceCode.Substring(startIndex, sourceCode.Length - startIndex);
            startIndex = sourceCode.IndexOf('.') +2;
            endIndex = sourceCode.IndexOf("/>", startIndex) -3;
            string cast = sourceCode.Substring(startIndex, endIndex - startIndex);

            //Get Plot
            sourceCode = WorkerClass.getSourceCode(pageURL);
            startIndex = sourceCode.IndexOf("Users:");
            sourceCode = sourceCode.Substring(startIndex, sourceCode.Length - startIndex);
            startIndex = sourceCode.IndexOf("</div>");
            endIndex = sourceCode.IndexOf("<div", startIndex);
            sourceCode = sourceCode.Substring(startIndex, endIndex - startIndex);
            startIndex = sourceCode.IndexOf("<p>") +7;
            endIndex = sourceCode.IndexOf("</p>");
            string plot = sourceCode.Substring(startIndex, endIndex - startIndex);

            //Get Rating
            sourceCode = WorkerClass.getSourceCode(pageURL);
            startIndex = sourceCode.IndexOf("infobar");
            sourceCode = sourceCode.Substring(startIndex, sourceCode.Length - startIndex);
            startIndex = sourceCode.IndexOf("alt=") +5;
            endIndex = sourceCode.IndexOf("src=", startIndex) -2;
            string rating = sourceCode.Substring(startIndex, endIndex - startIndex);

            //Get Release Date
            sourceCode = WorkerClass.getSourceCode(pageURL);
            startIndex = sourceCode.IndexOf("infobar");
            sourceCode = sourceCode.Substring(startIndex, sourceCode.Length - startIndex);
            startIndex = sourceCode.IndexOf("nobr");
            endIndex = sourceCode.IndexOf("</div>", startIndex);
            sourceCode = sourceCode.Substring(startIndex, endIndex - startIndex);
            startIndex = sourceCode.IndexOf("dates") +11;
            endIndex = sourceCode.IndexOf("</a") -4;
            string releaseDate = sourceCode.Substring(startIndex, endIndex - startIndex);

            //Get link to Cover Image
            sourceCode = WorkerClass.getSourceCode(pageURL);
            startIndex = sourceCode.IndexOf("img_primary");
            sourceCode = sourceCode.Substring(startIndex, sourceCode.Length - startIndex);
            startIndex = sourceCode.IndexOf("<img src=") + 10;
            endIndex = sourceCode.IndexOf(".jpg", startIndex) +4;
            string coverURL = sourceCode.Substring(startIndex, endIndex - startIndex);

            //Update movieTable with scraped data for the current title
            var comd = new SqlCommand("UPDATE movieTable SET director=@director, cast=@cast, plot=@plot, rating=@rating, releaseDate=@releaseDate, coverURL=@coverURL WHERE title=@title", con);
            comd.Parameters.AddWithValue("@title", title);
            comd.Parameters.AddWithValue("@director", director);
            comd.Parameters.AddWithValue("@cast", cast);
            comd.Parameters.AddWithValue("@plot", plot);
            comd.Parameters.AddWithValue("@rating", rating);
            comd.Parameters.AddWithValue("@releaseDate", releaseDate);
            comd.Parameters.AddWithValue("@coverURL", coverURL);
            con.Open();
            //Add to DB
            command.ExecuteNonQuery();
            con.Close();
        }

        this.movieTableTableAdapter.Fill(this.movieLibraryDBDataSet.movieTable);

Ответы [ 2 ]

3 голосов
/ 22 апреля 2011

Ваше последнее выполнение использует объект command вместо объекта comd, который вы определили позже для обновления.

1 голос
/ 22 апреля 2011

Записи уже существуют?Я думаю, что вам нужно сделать вставку.ОБНОВЛЕНИЕ только обновляет существующие записи.

...