I am trying to figure out how to use the MySql In cluse with ASP.NET C#. Here is my code
var WebSites = string.Join(",", wsl.Select(x => "'" + x.DomainUrl + "'").ToArray());
string q = "select Id, Url, Title, Date, ImageUrl from post where WebSiteUrl IN (#Url)";
When I dont use parameters this code works. When I include parameters I get no results from the query.
Here is my code for parameters
cmd.Parameters.Add("#Urls", MySqlDbType.Text).Value = WebSites;
here is whole code
public static IList<Post> FindPostsByWebSiteList(IEnumerable<WebSite> wsl)
{
var pl = new List<Post>();
var WebSites = string.Join(",", wsl.Select(x => "'" + x.DomainUrl + "'").ToArray());
string q = "select Id, Url, Title, Date, ImageUrl from post where WebSiteUrl IN (#Urls)";
using (MySqlConnection con = new MySqlConnection(WebConfigurationManager.ConnectionStrings["MySqlConnectionString"].ToString()))
{
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.GetString("Url");
p.Title = reader.GetString("Title");
p.Date = reader.GetDateTime("Date");
p.ImageUrl = reader.GetString("ImageUrl");
pl.Add(p);
}
return pl;
}
}
}
I have found the answer. Here it is
public static IList<Post> FindPostsByWebSiteList(string[] urls)
{
var pl = new List<Post>();
var urlArray = urls.Select((x,y) => "#url" + y.ToString()).ToArray();
var urlsJoined = string.Join(",", urlArray);
string q = string.Format("select Id, Url, Title, Date, ImageUrl from post where WebSiteUrl IN ({0})", urlsJoined);
using (MySqlConnection con = new MySqlConnection(WebConfigurationManager.ConnectionStrings["MySqlConnectionString"].ToString()))
{
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;
}
}
}
You have referenced #Url instead of #Urls
maybe just a typo in your question though
The IN statement should expect an Array of strings, and you are passing a single string
Your final SQL is looking like this:
select Id, Url, Title, Date, ImageUrl from post where WebSiteUrl IN ('url1,url2,url3')
Instead of
select Id, Url, Title, Date, ImageUrl from post where WebSiteUrl IN ('url1', 'url2', 'url3')
Check this question:
Add List<int> to a mysql parameter
Related
I want to insert data into a row in PostgreSQL from NPGSQL, but there is something wrong with my query string. Can you please suggest modify it?
public IActionResult Create(string item_name, string item_count, string item_size)
{
using var connection = new NpgsqlConnection(connString);
connection.Open();
string query = #"INSERT INTO public.""items""(""item_count"",""item_name"",""item_size"")VALUES ('"+item_count+item_count+item_count+"')";
using var command = new NpgsqlCommand(query, connection);
int result = command.ExecuteNonQuery();
if (result < 0)
{
return Error();
}
return View(nameof(Create));
}
You can do it in this way.
You have forgotten to add "," between the values and also add quotes if the value is string or date.
public IActionResult Create(string item_name, string item_count, string item_size)
{
using var connection = new NpgsqlConnection(connString);
connection.Open();
string query = String.Format(#"INSERT INTO public.""items""(""item_count"",""item_name"",""item_size"")VALUES('{0}','{1}','{2}');" , item_count , item_count ,item_count);
using var command = new NpgsqlCommand(query, connection);
int result = command.ExecuteNonQuery();
if (result < 0)
{
return Error();
}
return View(nameof(Create));
}
trying to update a column of null values with instagramIds, this is my current approach but the console app just keeps running and doesn't update any values in the database.
public static async Task<InstagramUser> ScrapeInstagram(string url)
{
using (var client = new HttpClient())
{
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
// create html document
var htmlBody = await response.Content.ReadAsStringAsync();
var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(htmlBody);
// select script tags
var scripts = htmlDocument.DocumentNode.SelectNodes("/html/body/script");
// preprocess result
var uselessString = "window._sharedData = ";
var scriptInnerText = scripts[0].InnerText
.Substring(uselessString.Length)
.Replace(";", "");
// serialize objects and fetch the user data
dynamic jsonStuff = JObject.Parse(scriptInnerText);
dynamic userProfile = jsonStuff["entry_data"]["ProfilePage"][0]["graphql"]["user"];
List<String> columnData = new List<String>();
//Update database query
string connectionString = #"Server=myProject-dev-db.cothtpanmcn7.ap-southeast-2.rds.amazonaws.com;Database=Projectdb;User Id=testadmin;Password=U8gs7vb7C7yvakXf;MultipleActiveResultSets=true;Trusted_Connection=False;";
using (SqlConnection con = new SqlConnection(connectionString))
{
//get null values from database
string query = "Select * from ApplicationUser where InstagramId is null";
using (SqlCommand command = new SqlCommand(query, con))
{
command.Connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
columnData.Add(reader.GetString(0));
}
}
}
for (int index = 0; index < columnData.Count(); index++)
{
//get username and scrape info
var instagramInfo = new InstagramUser
{
Id = userProfile.id,
};
columnData.Add(instagramInfo.ToString());
}
SqlCommand cmd = new SqlCommand("Update ApplicationUser Set InstagramId = '" + columnData + "'" + "where InstagramUsername = '" + userprofile.username + "'", con);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
// create an InstagramUser
var instagramUser = new InstagramUser
{
FullName = userProfile.full_name,
FollowerCount = userProfile.edge_followed_by.count,
FollowingCount = userProfile.edge_follow.count,
Id = userProfile.id,
url = url
};
return instagramUser;
}
else
{
throw new Exception($"Something wrong happened {response.StatusCode} - {response.ReasonPhrase} - {response.RequestMessage}");
}
}
}
The current output:
{"FullName":null,"FollowerCount":0,"FollowingCount":0,"Id":"6978701146","url":null}
{"FullName":null,"FollowerCount":0,"FollowingCount":0,"Id":"6978701146","url":null}
{"FullName":null,"FollowerCount":0,"FollowingCount":0,"Id":"6978701146","url":null}
{"FullName":null,"FollowerCount":0,"FollowingCount":0,"Id":"6978701146","url":null}
{"FullName":null,"FollowerCount":0,"FollowingCount":0,"Id":"6978701146","url":null}
My current approach is to create a list, add all instagramIDs which are null to that list. From there I add all instagramIds to that list after scraping Instagram for their usernames e.g. https://www.instagram.com/therock/?__a=1
then I update the column InstagramUsername with their instagram Ids
I've been having trouble (again) with some object-oriented code.
Currently I have a piece of code that populates a list with objects and its properties that goes like this:
foreach (var folder in pathList)
{
DirectoryInfo di = new DirectoryInfo(folder);
foreach (var file in di.GetFiles())
{
fileinfoList.Add(new FileInfo()
{
partNumber = Path.GetFileNameWithoutExtension(Convert.ToString(file)),
fileType = Path.GetExtension(Convert.ToString(file)),
lastDate = file.LastWriteTime,
released = 1,
checkedBy = null,
fullPath = Path.GetFullPath(Convert.ToString(folder)),
});
}
}
What I need is to add the baseID property to each of the objects. This is what I have currently:
foreach (var item in fileNameList)
{
if (fileinfoList.Select(m => m.partNumber == dummyString.ToString()) != null)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"data source = MYPC\SQLEXPRESS; database = MYDB; integrated security = TRUE";
string query = $#"SELECT id FROM MYTABLE WHERE fullpath= '{pathsToFilesNotOnDbList[y]}' ";
var cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
iD = Convert.ToInt16(dataReader["id"]);
fileinfoList.Select (f => f.baseID = iD) ;
Console.WriteLine(y);
y++;
}
conn.Close();
}
}
I want this loop to take the value of iD and assign it to the baseID property.
I can get the iD's just fine, however I'm aware that the lambda expression fileinfoList.Select (f => f.baseID = iD) does nothing currently.
Can someone help me out?
If you want to set baseId = iD to all the elements of the list fileinfoList, just use:
fileinfoList.ForEach(i => i.baseID = iD);
UPDATE: set different id to each element:
var index = 0;
while (dataReader.Read())
{
iD = Convert.ToInt16(dataReader["id"]);
fileinfoList[index].baseID = id;
Console.WriteLine(y);
y++;
index++;
}
One way or another you need to know which object in fileinfoList you want to update with each id value.
Assuming fullpath field is unique across the dataset and an identifier for the object in fileinfoList as well as MYTABLE you can make the following updates and it should work for you:
Update Query to include fullpath field in returned data:
string query = $#"SELECT id, fullpath FROM MYTABLE WHERE fullpath= '{pathsToFilesNotOnDbList[y]}' ";
Update assignment statement to filter fileinfoList by fullpath before attempting to assign the value from the db:
fileinfoList.FirstOrDefault(f => f.fullpath == dataReader["fullPath"]).baseID = iD;
Full code:
foreach (var item in fileNameList)
{
if (fileinfoList.Select(m => m.partNumber == dummyString.ToString()) != null)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"data source = MYPC\SQLEXPRESS; database = MYDB; integrated security = TRUE";
string query = $#"SELECT id, fullpath FROM MYTABLE WHERE fullpath= '{pathsToFilesNotOnDbList[y]}' ";
var cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
iD = Convert.ToInt16(dataReader["id"]);
fileinfoList.FirstOrDefault(f => f.fullpath == dataReader["fullPath"]).baseID = iD;
Console.WriteLine(y);
y++;
}
conn.Close();
}
}
I can't seem to get this working:
My table column headers are 'genre' 'artist' 'album'
and the params I'm passing in are (type, filter, value) ("artist", "genre", "Rock") where there are two rows in the db with "Rock" for the genre.
When I follow the debugger, the 'while (reader.Read())' must return false because the loop is never entered and thus nothing written to the List.
public static List<String> getWithFilter(String type, String filter, String value)
{
List<String> columnData = new List<String>();
string query = "SELECT #type FROM Music WHERE" +
" #filter = '#value'";
SqlConnection connection = Database.GetConnection();
SqlCommand getData = new SqlCommand(query, connection);
getData.Parameters.AddWithValue("#type", type);
getData.Parameters.AddWithValue("#filter", filter);
getData.Parameters.AddWithValue("#value", value);
connection.Open();
using (connection)
{
using (getData)
{
using (SqlDataReader reader = getData.ExecuteReader())
{
while (reader.Read())
{
columnData.Add(reader.GetString(0));
}
}
}
}
return columnData;
}
You cannot use parameters for the names of columns and you don't put quotes around them when using them. Right now your query is the equivalent of
SELECT 'artist' FROM Music WHERE 'genre' = '#value'
You can do the following instead.
string query = "SELECT " + type + " FROM Music WHERE " + filter + " = #value";
And just remove the lines that create the #type and #fitler parameters.
You're looking either for formatting or string interpolation (requires C# 6.0):
string query =
$#"SELECT {type}
FROM Music
WHERE {filter} = #value";
...
getData.Parameters.AddWithValue("#value", value);
Formatting is a bit more wordy:
string query = String.Format(
#"SELECT {0}
FROM Music
WHERE {1} = #value", type, filter);
I assuming that you're using .net 2
DateTime current = DateTime.Now;
Console.WriteLine(current);
SqlConnection conn = new SqlConnection();
string q = "SELECT #field FROM student";
SqlDataAdapter da = new SqlDataAdapter(q, conn);
da.SelectCommand.Parameters.AddWithValue("#field", "snName");
DataTable dt = new System.Data.DataTable();
conn.Open();
da.Fill(dt);
conn.Close();
List<string> names = new List<string>();
foreach (DataRow dr in dt.Rows)
{
names.Add(dr[0].ToString());
}
Console.WriteLine("Fetching {0} data for {1}", names.Count, DateTime.Now - current);
Console.ReadKey();
You can use lambda expression to mapping the datatable in .net >4
I want to use json to my android project. I am having some problem how to use json with .net. My code :
string stroutput = "";
try
{
string conStr = #"data source=.;database=Kelepir;Integrated Security=True;";
SqlConnection connection = new SqlConnection(conStr);
connection.Open();
string myquery = "select ProductID,ProductName,CategoryName,UnitPrice from Products";
SqlCommand cmd = new SqlCommand(myquery, connection);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
var nes = new
{
ProductID = reader["ProductID"].ToString(),
ProductName = reader["ProductName"].ToString(),
CategoryName = reader["CategoryName"].ToString(),
UnitPrice = reader["UnitPrice"].ToString()
};
stroutput = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(nes);
Response.Write(stroutput);
}
}
catch (Exception ex)
{
stroutput = "ERROR : " + ex.Message;
}
But my json has not this marks : ",", and "[ ]".
My output :
{"ProductID":"1","ProductName":"Şeker","CategoryName":"Tatlı","UnitPrice":"20"}
{"ProductID":"2","ProductName":"Kuruyemiş","CategoryName":"Tuzl","UnitPrice":"200"}
{"ProductID":"3","ProductName":"Baklagil","CategoryName":"Sebze","UnitPrice":"100"}
{"ProductID":"4","ProductName":"Bulgur","CategoryName":"Sebze","UnitPrice":"10"}
I want this format to my code :
{ "table_name":
[
{"ProductID":"1","ProductName":"Şeker","CategoryName":"Tatlı","UnitPrice":"20"}, {"ProductID":"2","ProductName":"Kuruyemiş","CategoryName":"Tuzl","UnitPrice":"200"},
{"ProductID":"3","ProductName":"Baklagil","CategoryName":"Sebze","UnitPrice":"100"},
{"ProductID":"4","ProductName":"Bulgur","CategoryName":"Sebze","UnitPrice":"10"}]
}
How I can do this ? Thanks...
give this a shot:
var rowList = new List<object>();
while (reader.Read())
{
var nes = new
{
ProductID = reader["ProductID"].ToString(),
ProductName = reader["ProductName"].ToString(),
CategoryName = reader["CategoryName"].ToString(),
UnitPrice = reader["UnitPrice"].ToString()
};
rowList.Add(nes);
}
var serializeMe = new {table_name = rowList }
stroutput = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(serializeMe );
Response.Write(stroutput);
You are serializing each row. What you want to do is pacakge each row into a colleciton and then serialize the collection as a whole.