C#/MySQL - Set WinForm Access Date MySQL
So I created a MySQL Database which my form is able to access & login to. My goal for it is to be able to pull information from the MySQL Database into the form as a label (I know easy right?).
Example:
The hardest problem for me was figuring out how to store lets say a "Subscription" start/end date and be able to tell me on a label, how many days I had left on my subscription. All this using information for the database.
(Yes this database is for test purposes only no where near final.)
Created a table called edata.
Created fields the program would use
(Account Status/StartSub/EndSub)
My Question: How would I go about taking the dates entered and creating a value that I could use to show in the "Days Left Here" label?
I will create the table like this:
CREATE TABLE `test`.`New Table` (
`ID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`FirstName` VARCHAR(45),
`LastName` VARCHAR(45),
`Username` VARCHAR(45),
`Password` VARCHAR(45),
`Account` INTEGER UNSIGNED,
`StartSub` DATETIME,
`EndSub` DATETIME,
PRIMARY KEY (`ID`)
)
ENGINE = InnoDB;
Then query like this:
using (MySqlConnection conn = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "select * from edata where id = 1;";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
DateTime dateStart = Convert.ToDateTime(dt.Rows[0]["StartSub"]);
DateTime dateEnd = Convert.ToDateTime(dt.Rows[0]["EndSub"]);
if (DateTime.Now >= dateStart && DateTime.Now <= dateEnd)
{
TimeSpan ts = dateEnd - DateTime.Now;
label1.Text = "Active";
label2.Text = ts.TotalDays + " day(s) left";
}
else
{
label1.Text = "Expired";
label2.Text = "0 day left";
}
}
}
If you can parse the values out it is pretty simple, for example:
string end_date_string = "2014-09-24";
string start_date_string = "2014-09-18";
DateTime end_date = DateTime.Parse(end_date_string); // parse end date
DateTime start_date = DateTime.Parse(start_date_string); // parse start date
TimeSpan dur = end_date.Subtract(start_date); // total duration
TimeSpan timeleft = end_date.Subtract(DateTime.Now); // how much time left until we hit the end_date
Label l;
l.Text = timeleft.Days.ToString();
// l.Text = timeLeft.Hours.ToString();
// l.Text = timeleft.Minutes.ToString();
Related
I have a table of data in Access
DateTimeLog has date/time datatype while the other rest are string.
I need to get the total number of row of data at the last hour of system date with specified ModelLog. But I could not think of a correct structure of the query using MS Access as I am very new to MS Access.
Below shows how I insert the data:
DateTime now = DateTime.Now;
var today = now.ToString("g");
DateTime d = DateTime.Parse(today);
const string sql = #"INSERT INTO timer(DateTimeLog, ShiftLog, CTLog, WorkcellLog, ModelLog, StationLog)VALUES(#d, #shift, #ct, #wc, #wm, #ws)";
OleDbCommand cmd = new OleDbCommand(sql, connection);
cmd.Parameters.Add("#d", OleDbType.DBTimeStamp).Value = d;
cmd.Parameters.Add("#shift", OleDbType.VarChar).Value = shiftlb.Text;
cmd.Parameters.Add("#ct", OleDbType.VarChar).Value = timerlb.Text;
cmd.Parameters.Add("#wc", OleDbType.VarChar).Value = wclb.Text;
cmd.Parameters.Add("#wm", OleDbType.VarChar).Value = mlb.Text;
cmd.Parameters.Add("#ws", OleDbType.VarChar).Value = slb.Text;
try
{}
catch(exception e)
{}
Ok, so you clearly know how to run a database query with parameters, you just need to run this query as ExecuteScalar, casting the result to an int
SELECT COUNT(*) FROM timer WHERE dateTimeLog >= #d
And then set your d parameter to an hour ago
cmd.Parameters.Add("#d", OleDbType.Date).Value = DateTime.Now.AddHours(-1);
Side note I would recommend not round tripping via string just to cut the seconds off a time. Instead consider:
var d = DateTime.Now;
d = d.AddTicks( -(d.Ticks % (60*TimeSpan.TicksPerSecond)));
Or maybe
var d = DateTime.Now;
d = d.AddMilliseconds(-d.Milliseconds).AddSeconds(-d.Seconds);
I found out another way of getting the number of data within the same hour. Create two new columns, HourID and TodayDate both represent current hour in 24hours format and today's date respectively. Insert the data accordingly.
Getting count of data:
const string sql = #"SELECT COUNT(*) FROM timer WHERE HourID = #h AND TodayDate = #td AND ModelLog = #m";
OleDbCommand cmd = new OleDbCommand(sql, connection);
cmd.Parameters.Add("#h", OleDbType.VarWChar).Value = DateTime.Now.ToString("%H");
cmd.Parameters.Add("#td", OleDbType.VarWChar).Value = DateTime.Now.ToShortDateString();
cmd.Parameters.Add("#m", OleDbType.VarWChar).Value = mlb.Text;
I have a chart in asp.net web form page. i want to fill it with a custom query created by joining two variables from the same sql table.
Here is the code (query):
String year2 = Convert.ToString(dropDownStartYear.Text);
String month2 = Convert.ToString(dropDownMonth2.Text);
String day2 = Convert.ToString(dropDownDay2.Text);
String hour2 = Convert.ToString(dropDownHour2.Text);
String minute2 = Convert.ToString(dropDownMinute2.Text);
String year3 = Convert.ToString(dropdownYear3.Text);
String month3 = Convert.ToString(dropDownMonth3.Text);
String day3 = Convert.ToString(dropDownDay3.Text);
String hour3 = Convert.ToString(dropDownHour3.Text);
String minute3 = Convert.ToString(dropDownMinute3.Text);
SqlConnection connection = ConnectionManager.getConnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT id, temperature, year, month, day , hour, minu from datab where year = #year and month=#month and day=#day and hour=#hour and minu=#minute ; ";
cmd.Parameters.AddWithValue("#year", year2);
cmd.Parameters.AddWithValue("#month", month2);
cmd.Parameters.AddWithValue("#day", day2);
cmd.Parameters.AddWithValue("#hour", hour2);
cmd.Parameters.AddWithValue("#minute", minute2);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
}
where i want to select a start date and time (year, month, day, hour, minute) from a table in sql server and also select an end date with same variables.
then i want to draw the "temperature" that varies from the start time to the end time.
any help there?
Try this query, building DateTime objects from the date parts in the input and stored in your table. That should make it easier to compare and restrict your return values by the selected input values:
cmd.CommandText = #"select [id], [temperature], [year], [month], [day], [hour], [minu]
from datab
where DATETIMEFROMPARTS([year], [month], [day], [hour], [minu], 0, 0)
between DATETIMEFROMPARTS(#year2, #month2, #day2, #hour2, #minute2, 0, 0)
and DATETIMEFROMPARTS(#year3, #month3, #day3, #hour3, #minute3, 0, 0)";
// beginning of date range
cmd.Parameters.AddWithValue("#year2", year2);
cmd.Parameters.AddWithValue("#month2", month2);
cmd.Parameters.AddWithValue("#day2", day2);
cmd.Parameters.AddWithValue("#hour2", hour2);
cmd.Parameters.AddWithValue("#minute2", minute2);
// end of date range
cmd.Parameters.AddWithValue("#year3", year3);
cmd.Parameters.AddWithValue("#month3", month3);
cmd.Parameters.AddWithValue("#day3", day3);
cmd.Parameters.AddWithValue("#hour3", hour3);
cmd.Parameters.AddWithValue("#minute3", minute3);
Try this query...
cmd.CommandText = "SELECT id, temperature, year, month, day , hour, minu from datab
where CONVERT ( datetime , cast(year as varchar)+'-'+cast(month as varchar)+'-'+cast(day as varchar)+' '+cast(hour as varchar)+':'+cast(minute as varchar)+':'+'00' , 20) >= CONVERT ( datetime , #yearfrom+'-'+#monthFrom+'-'+#dayFrom+' '+#hourFrom+':'+#minuteFrom+':'+'00' , 20)
and CONVERT ( datetime , cast(year as varchar)+'-'+cast(month as varchar)+'-'+cast(day as varchar)+' '+cast(hour as varchar)+':'+cast(minute as varchar)+':'+'00' , 20) <= CONVERT ( datetime , #yearTo+'-'+#monthTo+'-'+#dayTo+' '+#hourTo+':'+#minuteTo+':'+'00' , 20);";
i have a web service in which training number is assigning as per my database
there is a line
dates + "1"; this lines add 1 in date
like 27012017 will become 270120171
then i convert this into int64
newid = Convert.ToInt64(dates);
but now i want to add trainer id in this
so i updated my line with this
dates ="00"+trainerid +"-"+ dates + "1";
newid = Convert.ToInt64(dates);
the error is coming input string is not in correct format,
i know this is because of the addition of +"-"+
but i want to store the data in this format only
and my whole portion look like
DateTime dt = DateTime.Now;
string dates = dt.ToString();
dates = dates.Replace("-", "");
dates = dates.Substring(0, 8);
SqlCommand cmdbill = new SqlCommand("select top 1 * from listmybill where bill_id like #trid order by bill_id desc", con);
con.Open();
cmdbill.Parameters.AddWithValue("#trid", "%" + dates + "%");
SqlDataReader dr = cmdbill.ExecuteReader();
while (dr.Read())
{
value = dr["bill_id"].ToString();
}
con.Close();
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdbill);
DataTable dat = new DataTable();
da.Fill(dat);
if (dat.Rows.Count > 0)
{
newid = Convert.ToInt64(value);
newid = newid + 1;
}
else
{
dates ="00"+trainerid +"-"+ dates + "1";
newid = Convert.ToInt64(dates);
}
con.Close();
what should i do here,
i want to enter the data like 001-270120171
and if i convert toInt64 into string,
there can be problem when a row found in the table
if (dat.Rows.Count > 0)
{
newid = Convert.ToInt64(value);
newid = newid + 1;
}
what i need to do now?
i want to store this into my database
I hardly think you will be doing mathematical calculations on this training number string. I suggest that you convert the int in your database into a varchar using alter statement. Then you you will be able to store the training number in whichever format you like.
You can change new id to string and do the following
if (dat.Rows.Count > 0)
{
newid = Convert.ToString(Convert.ToInt64(value)+1);
}
else
{
newid="00"+trainerid +"-"+ dates + "1";
}
I'm getting an issue when executing a reader to retrieve some DateTimes from a table.
First, I have one page transferring over some variables to another page:
//calStart.SelectedDate is a DateTime value
Response.Redirect("SpecialReports_Results.aspx?userListValues=" + userListValues + "&groupListValues=" + groupListValues + "&calSelected=" + calStart.SelectedDate);
Then, on the new page:
//To retrieve the values that were sent over
string userListValues = Request.QueryString["userListValues"];
string groupListValues = Request.QueryString["groupListValues"];
string dateSelected = Request.QueryString["calSelected"];
// SQL Server connection stuff + string argument
SqlCommand command2 = new SqlCommand();
command2.Connection = gconn;
String sql2 = "SELECT MAX([Day]) as TheDay FROM Days WHERE User_ID = #User_ID AND [Day] < '#dateSelected' AND NOT EXISTS (SELECT 1 FROM Days WHERE User_ID = #User_ID AND [DAY] >= '#dateSelected')";
command2.CommandText = sql2;
command2.Parameters.Add(new SqlParameter("#User_ID", ""));
command2.Parameters.Add(new SqlParameter("#dateSelected", dateSelected));
List<string> dates = new List<string>();
//userID is a List<string>
foreach (string str in userID)
{
command2.Parameters["#User_ID"].Value = str;
using (SqlDataReader reader = command2.ExecuteReader())
{
while (reader.Read()) //Getting error here: Conversion failed when converting datetime from character string.
{
if (reader.HasRows)
{
dates.Add(reader["Day"].ToString());
}
}
}
}
The table Days is set up like so:
User_ID | Day
----------------------------------
10 | 2010-11-09 00:00:00.000
20 | 2015-12-06 00:00:00.000
30 | 2012-01-12 00:00:00.000
40 | 2013-07-23 00:00:00.000
The Day column is of type DateTime.
I have tried converting the string dateSelected and the List<string> dates to DateTime by doing:
DateTime confirmedDate = DateTime.Parse(dateSelected);
List<DateTime> dates = new List<DateTime>()
But I get the same error.
Note: The SQL statement does work when executed in Microsoft's SQL Server Management Studio.
I think you need to delete single quotes on your '#dateSelected'.
With that, your code see it as a string literal, not a parameter.
String sql2 = "SELECT MAX([Day]) as TheDay FROM Days WHERE User_ID = #User_ID AND [Day] < #dateSelected AND NOT EXISTS (SELECT 1 FROM Days WHERE User_ID = #User_ID AND [DAY] >= #dateSelected)";
Since there is no implicit conversation from string to datetime, your reader try to convert this #dateSelected string literal to datetime and it fails.
How to store date as "1" and month as "1" to mysql database by using c#,(for example 1-1-1987),i can get year from the variable frdt,so i need to store for example 1-1-frdt.
string frdt = drow1["release_year"].ToString();
i would pass it into a DateTime object and insert that one into your database
string frdt = drow1["release_year"].ToString();
DateTime Result = new DateTime(int.Parse(frdt), 1, 1);
string Command = "INSERT INTO TABLENAME (COLUMNNAME) VALUES (#DATEVALUE);"; // TODO
using (MySqlConnection mConnection = new MySqlConnection(ConnectionString))
{
mConnection.Open();
using (MySqlCommand myCmd = new MySqlCommand(Command, mConnection))
{
myCmd.Parameters.AddWithValue("#DATEVALUE", Result);
int RowsAffected = myCmd.ExecuteNonQuery();
}
}
If you're storing a date then it should be stored as a binary date, not as text. It's hard to tell whether you're doing that or not but you absolutely should. The fact that you're storing a year, which is a number, in a string variable is not encouraging. You should be storing the year in an int and then creating a DateTime like so:
var myDate = new DateTime(year, 1, 1);
where year is the int containing the year. You then save that to your database as you would any other data, using a parameter one would hope, e.g.
var command = new MySqlCommand("UPDATE MyTable SET MyDate = #MyDate WHERE ID = #ID", connection);
command.Parameters.AddWithValue("#MyDate", myDate);