J’essaie de comprendre comment utiliser MySql In cluse avec ASP.NET C #. Voici mon code
var WebSites = ssortingng.Join(",", wsl.Select(x => "'" + x.DomainUrl + "'").ToArray()); ssortingng q = "select Id, Url, Title, Date, ImageUrl from post where WebSiteUrl IN (@Url)";
Quand je n’utilise pas de parameters, ce code fonctionne. Lorsque j’inclus des parameters, la requête ne donne aucun résultat.
Voici mon code pour les parameters
cmd.Parameters.Add("@Urls", MySqlDbType.Text).Value = WebSites;
voici le code entier
public static IList FindPostsByWebSiteList(IEnumerable wsl) { var pl = new List(); var WebSites = ssortingng.Join(",", wsl.Select(x => "'" + x.DomainUrl + "'").ToArray()); ssortingng q = "select Id, Url, Title, Date, ImageUrl from post where WebSiteUrl IN (@Urls)"; using (MySqlConnection con = new MySqlConnection(WebConfigurationManager.ConnectionSsortingngs["MySqlConnectionSsortingng"].ToSsortingng())) { using (MySqlCommand cmd = new MySqlCommand(q, con)) { cmd.Parameters.Add("@Urls", MySqlDbType.Text).Value = WebSites; con.Open(); var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); while (reader.Read()) { var p = new Post(); p.Id = reader.GetInt32("Id"); p.Url = reader.GetSsortingng("Url"); p.Title = reader.GetSsortingng("Title"); p.Date = reader.GetDateTime("Date"); p.ImageUrl = reader.GetSsortingng("ImageUrl"); pl.Add(p); } return pl; } } }
Vous avez référencé @Url au lieu de @Urls
peut-être juste une faute de frappe dans votre question si
J’ai trouvé la réponse. C’est ici
public static IList FindPostsByWebSiteList(ssortingng[] urls) { var pl = new List (); var urlArray = urls.Select((x,y) => "@url" + y.ToSsortingng()).ToArray(); var urlsJoined = ssortingng.Join(",", urlArray); ssortingng q = ssortingng.Format("select Id, Url, Title, Date, ImageUrl from post where WebSiteUrl IN ({0})", urlsJoined); using (MySqlConnection con = new MySqlConnection(WebConfigurationManager.ConnectionSsortingngs["MySqlConnectionSsortingng"].ToSsortingng())) { using (MySqlCommand cmd = new MySqlCommand(q, con)) { for (int x = 0; x < urlArray.Length; x++) { cmd.Parameters.Add(urlArray[x], MySqlDbType.Text).Value = urls[x]; } con.Open(); var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); while (reader.Read()) { var p = new Post(); p.Id = reader.GetInt32("Id"); p.Url = reader.GetString("Url"); p.Title = reader.GetString("Title"); p.Date = reader.GetDateTime("Date"); p.ImageUrl = reader.GetString("ImageUrl"); pl.Add(p); } return pl; } } }
L’instruction IN doit s’attendre à un tableau de chaînes et vous passez une chaîne unique.
Votre SQL final ressemble à ceci:
select Id, Url, Title, Date, ImageUrl from post where WebSiteUrl IN ('url1,url2,url3')
Au lieu de
select Id, Url, Title, Date, ImageUrl from post where WebSiteUrl IN ('url1', 'url2', 'url3')
Vérifiez cette question:
Ajouter la liste