Sending SQL string in for every calculated date - c#

I have a sql string now, and I need to send it in, for every day between 2 dates. like, if the first date yould be, 01.01.0001 and the last date would be 03.01.0001 then, the string should be send 3 times in with every date (01. + 02. + 03.01.0001)
Any ideas for I can integrate that in my script when I already need to send the string in for every selected member ID?
That means, if I have 3 IDs, and 3 days, there would be 3 strings for every ID = 9 strings per total.
Please note, that the dates are dynamic as well as the amout of IDs.
For now, I have:
foreach (DataRow row in m_dt.Rows) {
foreach (var item in row.ItemArray) {
string sqlString = "INSERT INTO [table] ([id] ,[day] ,[month] ,[year]) VALUES('" + item + "', '" + reason + "', '10', '08', '2016', '1' )";
Sendin( sqlString );
}

Related

cant store an HTML page when ncarchar(max) is capped at 4000 characters

To put it simple, how to increase the cap of nvarchar(MAX) to actually hold 280MB of text and not just 8000MB (correct me if I'm wrong)?
So, for my finals project I'm making a web-crawler for a client that wants its own customized search engine for their library website, but my problem arises when i try to store the infomation that the crawlers retrieve.
Specifically the problem I have is that even tho I set the column "HTML" to nvarchar(MAX), which should be able to hold 2GB of data, it wont save any infomation to it, in this case 280MB, cause it's too long.
I did try shortening the length of the text to be saved and when I made it sufficiently short enough it finally agreed to save the data, so from what I can understand it's capped.
EDIT: Code examples as requested
page container class:
public class Page
{
public int ID = -1;
public String URL;
public String HeadLine;
public List<String> Tags;
public String Description;
public String HTML;
public DateTime lastUpdate;
}
Code snippet when crawler saves the page that it has retrieved:
//Save Page content to Database
Page page = new Page();
page.URL = url;
page.HeadLine = headline;
page.Tags = tags.Split(',').Where(s => !string.IsNullOrWhiteSpace(s)).ToList();
page.Description = description;
page.HTML = HTML;
page.lastUpdate = DateTime.Today;
new DBpage(Settings.instance.DBaddress,
Settings.instance.DBname).SavePage(page);
Method used for storing the data:
public void SavePage(Page page) {
String SqlString = "";
//Check is a page by the given URL already exists in the database and assign the SQL string acordingly
Page foundPage = GetPage(page.URL);
if(foundPage == null) {
SqlString = "INSERT INTO WebContent " +
"VALUES (#URL, #HeadLine, #Tags, #Description, #HTML, #LastUpdate)";
}
else {
SqlString = "UPDATE WebContent " +
"SET URL = #URL, HeadLine = #HeadLine, Tags = #Tags, Description = #Description, HTML = #HTML, LastUpdate = #LastUpdate " +
//"SET URL = '" + page.URL + "', HeadLine = '" + page.HeadLine + "', Tags = '" + String.Join(",", page.Tags) + "', Description = '" + page.Description + "', HTML = '" + page.HTML.Replace("'", "''") + "', LastUpdate = " + page.lastUpdate + " " +
"WHERE ID = " + foundPage.ID;
}
//Assign all variables and execute the SQL
try {
using(DBaccess db = new DBaccess(dblocation, dbname)) {
String html = page.HTML.Replace("'", "''"); //Replace all single quotes with double "single quotes" to escape the first single quote.
SqlCommand sqlCmd = db.GetSqlCommand(SqlString);
sqlCmd.Parameters.AddWithValue("#URL", page.URL);
sqlCmd.Parameters.AddWithValue("#HeadLine", page.HeadLine);
sqlCmd.Parameters.AddWithValue("#Tags", String.Join(",", page.Tags));
sqlCmd.Parameters.AddWithValue("#Description", page.Description);
sqlCmd.Parameters.AddWithValue("#HTML", html);
sqlCmd.Parameters.AddWithValue("#LastUpdate", page.lastUpdate);
sqlCmd.ExecuteNonQuery();
}
}
catch(SqlException e) {
Console.WriteLine(e.Message);
}
}
The unfortunate result that puzzles me:
nvarchar(max) type does allow to store up to 2GB of data. For nvarchar it means about 1 billion characters, because N types store text in 2-bytes per character unicode.
nvarchar [ ( n | max ) ]
Variable-length Unicode string data. n defines the string length
and can be a value from 1 through 4,000. max indicates that the
maximum storage size is 2^30-1 characters. The maximum storage size in
bytes is 2 GB. The actual storage size, in bytes, is two times the
number of characters entered + 2 bytes.
Most likely your problem is somewhere in the procedure that tries to INSERT such large text. The first thing that comes to mind is some timeout. It will take a while to upload 280MB of data to the server, so examine the details of failure (look through the error messages and exceptions) to gather clues of what is going wrong.
Few things to check:
Double check the type of the HTML column in the database.
Maybe SSMS doesn't display the long value correctly. Try to run
SELECT LEN(HTML) FROM YourTable
to verify the length of the stored string.
Overall, just step through the code in the debugger and verify that all variables have expected values.

How to cut string from combobox import from query

I need help with my comboboxes.
An application to the value selected in the first combo imported dates in the second and the third combo combo. Only the dates look like this:2009-01-01 12:00:00AM. I want to cut 12:00:00AM. My query is:
string command2 = "select God_MinQ,God_AverQ,God_MaxQ,min(Dat) from hydgod where station='"
+ comboBox1.SelectedItem.ToString() + "' and Dat between '"
+ comboBox2.SelectedItem.ToString() + "' and '" + comboBox3.SelectedItem.ToString()
+ "' group by year(dat),month(Dat)";
Where can I format string in combobox2 and combobox3?
Another thing I wanted to ask you. When the user chooses from combo2 starting date to date as 2009-01-01 to 2010-01-01 Mesagebox out in year 2010, and he has chosen for the year 2009. How can I fix this.
Here is a link to the screenshot:
https://s30.postimg.org/60nuoocdd/Untitled.jpg
If your comboboxes containe DateTime-Values you can format them like this:
DateTime value = (DateTime)comboBox2.SelectedItem;
String valueString = value.ToString("MMMM dd, yyyy");
If you need a differen formationg check out the MSDN Entry
You should really consider using Sql Parameter like #Reniuz suggested.
This prevents SQL Injection attack and helps in general by better readability of your code and easier parsing of values

Return DB results within Date Range

In my view, I have an input and select tags for the user to enter a start and end date.
When submitted, The controller will search the Model/Database and return entries within the above range.
In my DB, the start and end dates are written as "nvarchars" and in my controller they are taken as strings
Code and Images for reference:
public ActionResult timePeriod(string time)
{
//Start: month, day, year End: month, day, year --> Numeric values
string[] times = time.Split(',');
string start = times[0] + " " + times[1] + " " + times[2];
string end = times[3] + " " + times[4] + " " + times[5];
//Sample code to test the start date
viewModel.Tasks = db.Tasks.Where(s => s.StartTime.Contains(start)).ToList();
}
a snippet of the Database values:
Are there any LINQ expression to do this?
As the dates are strings, you've nothing better other than using what you have suggested already:
viewModel.Tasks = db.Tasks.Where(s => s.StartTime.Equals(start)).ToList();
I would use Equals as that will be quicker for you. Using Contains is basically like doing a T-SQL LIKE which is much slower.
SELECT *
FROM Table
WHERE StartDate LIKE 'blah'
Using Equals will result in the following equivalent:
SELECT *
FROM Table
WHERE StartDate = 'blah'
Which is much more efficient.

I have mistake in SQL Server database

I want to compare date entering from a combobox as string with the date that saved into SQL Server database,then summation some values X but comparison doesn't work ...
string from = (comboBox4.Text+ '/' + comboBox5.Text + '/' + comboBox6.Text+ " 00:00:00 AM");
string to = (comboBox1.Text+ '/' + comboBox2.Text + '/' + comboBox3.Text);
cmd.CommandText = "SELECT * from issued where issued.Date >='" +from + " ' And issued.Date < '" + to + " ' "; //مقارنة الاسم
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
item = new ListViewItem(dr[0].ToString());
item.SubItems.Add(dr[4].ToString());
f6.listView1.Items.Add(item);
x += Convert.ToInt16(dr[4]);
}
}
Help me please..
As Marc stated above, you really should be careful of sql injection attacks here. Look it up and do some research because you'll suddenly find you have a compromised server someday.
Is your Date column of type Date or DateTime? If it's DateTime, then simply comparing on a specific date does not include that date for the upper bound. For instance, if your dates are:
From: 1/1/2013
To: 1/1/2014
Then your comparison would not return any values from 1/1/2014, and the last date included in the search would actually be 12/31/2013.
Add a little more specifics to your question regarding what values you are actually sending in your sql and what the types are in your db and you'll get a better answer!
Good luck!

graphing non sequential data C# and mysql

I'm trying to display in a graph (Winforms/C#) the total amount from one column vs unit of time (in this case month) - so it would be a amount vs time graph. The problem is that the user would like the freedom of lets say - choosing the totals for January and June and compare them in a single graph (so the total for the month of January would be represented as a bar next to June's total's bar). I already capture the selected months (also, I have the graph control on the for) within a list but where I am really stuck is to build the mysql statement and its something like this
selectdataforGraph = "SELECT SUM(Amount_Net) AS Total FROM testingproject.incomeinformation WHERE date";
foreach (int month in selectedMonth) {
selectdataforGraph += "between '" + selected_year+ "-" + month +
"'-1 AND '" + selected_year + "-"+month+ "-31' AND";
}
I know it has some space missing and some quotation mark problems - already ran the query and I figured as much but I don't think the in-between would work because I don't know how to AND the next part of it so if a user picks May then August would be between 2007-5-01 and 2007-5-30 AND 2007-8-01 and 2007-8-30???
EDIT: didn't seem MySQL was your DB...
Definitely use a parameterized query! However... to fit in with what you have and so you can test it quickly...
I think I would use DATEPART rather than BETWEEN....
var selectdataforGraph = "SELECT SUM(Amount_Net) AS Total FROM testingproject.incomeinformation WHERE ";
var monthList = string.Join(",", selectedMonth);
selectdataforGraph += " YEAR(date) = " + selected_year;
selectdataforGraph += " AND MONTH(date) in (" + monthList + ")";

Categories