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;
Related
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);
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();
I want to make passive them if a date is earlier than today from the recorded dates within database with update command.How can I do that by using single query in C#?
Colums: Tarih(nvarchar) , Durum(nvarchar)
For example;
if tarih<Datetime.Today.Date is set Durum='PASİF'
Code:
string sorgu = "select BitTarihi from Abonelikler";
SqlConnection gg = new SqlConnection(constr);
SqlCommand gg2 = new SqlCommand(sorgu,gg);
SqlDataReader gg3;
gg.Open();
gg3= gg2.ExecuteReader();
while (gg3.Read())
{
DateTime b1 = new DateTime();
DateTime b2 = new DateTime();
b1 = Convert.ToDateTime(gg3.GetString(0));
b2 = DateTime.Today.Date;
TimeSpan fark = new TimeSpan();
fark = b2 - b1;
if (fark.TotalDays > 0)
{
SqlConnection vv = new SqlConnection(constr);
SqlCommand vv2 = new SqlCommand("update Abonelikler set Durum='PASİF' where BitTarihi='" + b1.ToShortDateString() + "'", vv);
vv.Open();
vv2.ExecuteNonQuery();
vv.Close();
vv2.Dispose();
}
}
gg.Close();
gg2.Dispose();
Look at DATEDIFF function.
UPDATE Abonelikler SET Durum='PASIF'
WHERE DATEDIFF(DD, CONVERT(datetime, BitTarihi), GETDATE())>0
Also, please do not use concatenation of an SQL statement, use parameters. It's more safe and also sometimes concatenation of statement with parameters hampers server-side statement optimization.
Instead of updating the records why don't you decide the state at query level? Since you check this everyday there will be many unneeded updates.
SELECT BitTarihi, CASE WHEN DATEDIFF(DAY, BitTarihi, GetDate()) = 0 THEN 'AKTIF' ELSE 'PASIF' END DURUM FROM Abonelikler
This way you won't have to update your records.