C# Updating mySQLDateTime Datatable - c#

I'm having trouble updating a mySQL database with a datatable. I can do it with an INSERT statement, but the table fails the assignment when I insert a row with the error "Couldn't store <...> in date Column. I have millions of records to insert and I thought this way might be faster. I actually don't care about the time, just the date.
MySqlConnection con = new MySqlConnection();
con.ConnectionString = string.Format(#"server={0};userid={1};password={2};database={3};AllowZeroDatetime=True", srvr, user, pass, db);
MySqlCommand cmnd = new MySqlCommand();
cmnd.Connection = con;
con.Open();
cmnd.CommandText = "DROP TABLE IF EXISTS dateTest";
cmnd.ExecuteNonQuery();
cmnd.CommandText = "CREATE TABLE dateTest (date DATE, dateTime DATETIME)";
cmnd.ExecuteNonQuery();
string myDate = "2014-04-19";
string myDateTime = "2014-04-20 00:00:00";
//this code works
cmnd.CommandText = string.Format("INSERT INTO dateTest(date, dateTime) VALUES('{0}', '{1}')", myDate, myDateTime);
cmnd.ExecuteNonQuery();
MySqlDataAdapter da = new MySqlDataAdapter("SELECT * from dateTest", con);
MySqlCommandBuilder cb = new MySqlCommandBuilder(da);
DataTable tbl = new DataTable();
da.Fill(tbl);
foreach (DataRow row1 in tbl.Rows)
{
Debug.WriteLine(string.Format("{0} : {1}", row1["date"], row1["dateTime"]));
//returns: 4/19/2014 : 4/20/2014 12:00:00 AM
}
DataRow row2 = tbl.NewRow();
row2["date"] = myDate; //Errors here: Couldn't store <2014-04-19> in date Column. Expected type is MySqlDateTime.
row2["dateTime"] = myDateTime; //Also errors here: Couldn't store <2014-04-20 00:00:00> in dateTime Column. Expected type is MySqlDateTime.
tbl.Rows.Add(row2);
da.Update(tbl);

this is my first time trying to answer a question. Hope this help.
I think you have to convert the date to DateTime first before you can store it in mysql.
string myDateTime = "2014-04-20 00:00:00";
DateTime myDateTimeValue = DateTime.Parse(myDateTime);
Then
row2["dateTime"] = myDateTimeValue;
I have not tried it yet. Hope it works

Related

Get COUNT of data at the current hour of system date

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;

Oracle.ManagedDataAccess.Client.OracleException: 'ORA-01830: date format picture ends before converting entire input string'

I ma getting an error
Oracle.ManagedDataAccess.Client.OracleException: 'ORA-01830: date format picture ends before converting entire input string'
while finding out volume through a c# code and oracle query:
public DataTable empcount(string strtdate, string enddate)
{
string cString = ConfigurationManager.ConnectionStrings["greft"].ToString();
OracleConnection conn = new OracleConnection(cString);
OracleCommand cmd2 = new OracleCommand();
cmd2.CommandText = "Select (sum(emp)) from emp_rec where emp_typ = 'M'and emp_stat!= 'ON'and trunc(join_start) >= TO_CHAR(TO_DATE(:sdate, 'DD-MM-YY'), 'DD-MON-YY') and trunc(join_end) <= TO_CHAR(TO_DATE(:edate, 'DD-MM-YY'), 'DD-MON-YY') ";
cmd2.Parameters.Add(":sdate", strtdate);
cmd2.Parameters.Add(":edate", enddate);
cmd2.Connection = conn;
OracleDataAdapter da = new OracleDataAdapter(cmd2);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Dispose();
return dt;
}
In the table the join_start and join_end has date in the format like '02-MAY-2019'. The :sdate & :edate input will be in the format of mm/dd/yyyy (e.g. 05/01/2019).
The column REQ_START_TIME is of data type VARCHAR2(11) with values such as 02-MAY-2019
The parameter value sdate is a String with values such as 05/01/2019
I see two problems
Trunc on a character column
trunc(REQ_START_TIME) - you should convert the string to DATE before truncating it (or even better store the value in a DATE column!)
Mask 'DD-MM-YY' for the value 05/01/2019
Convert the predicate to
where trunc(to_date(REQ_START_TIME,'DD-MON-YYYY')) >= TO_DATE(:sdate, 'DD/MM/YYYY')
Generall recommendation - do not store a DATE values in a character column in the database

Invalid column name on adapter fill

I am getting a System.Data.SqlClient.SqlException with additional information of an Invalid column name Jun on Fill function while I am entering 19-jun-2016 from the datetimePicker and here is a Jun is a month but it taking it as a column.
ReportForm.cs
public void MakeDailyReport(string givenDate, DataGridView view)
{
con.Open();
cmd = new SqlCommand("SELECT Date FROM FinalSales where Date = #datePicker", con);
cmd.Parameters.AddWithValue("#datePicker", givenDate);
cmd.ExecuteNonQuery();
DateTime dateObject = (DateTime)cmd.ExecuteScalar();
string dateObjectstring = Convert.ToString(dateObject.ToShortDateString());
string givenDateString = Convert.ToString(givenDate);
if (dateObjectstring == givenDateString)
{
DataTable dt = new DataTable();
adapt = new SqlDataAdapter("SELECT Date FROM FinalSales where Date = " + givenDate + "", con);
if (adapt != null)
{
adapt.Fill(dt);
view.DataSource = dt;
}
else
{
MessageBox.Show("No Record found againts that date");
con.Close();
}
}
else
{
con.Close();
}
}
Don't use string concatenation to build your query but sql parameters with the correct type. That will also prevent you from sql injection and other possible issues (like this one).
adapt = new SqlDataAdapter("SELECT [Date] FROM FinalSales where [Date] = #givenDate", con);
var dateParameter = adapt.SelectCommand.Parameters.Add("#givenDate", SqlDbType.DateTime);
dateParameter.Value = dateTimePicker.Value.Date; // not string but the correct type DateTime
Note that i've also used dateTimePicker.Value.Date to ignore the time portion.

C#: Sort DATATABLE with column date

I know it is a repeated question but i have tried much but i am getting exception
$exception {"String was not recognized as a valid DateTime."} System.Exception {System.FormatException}
Following is my code please check and guide
SQL QUERY
SELECT gangId as gang, respectPoints as respectPoints,DATE_FORMAT( purchasedDate, '%d-%m-%Y') as date_purchase FROM tbl_gang t where gangId=" + gangId
Data Access Layer Code
DataTable dt = new DataTable();
MySqlCommand cmd = conn.CreateCommand();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
cmd.CommandText = inAppPurchaseQuery;
da.Fill(dt)
Sorting Code
dt = gangRPObj.getGangRPLogsBL(gangId, fromDate, toDate);
var sortedTable = dt.AsEnumerable()
.OrderBy(r => DateTime.ParseExact(("date_purchase"),
"dd-mm-yyyy", null))
.CopyToDataTable();
Thanks
You are passing string to datetime conversion that's why exception is coming. Try
var orderedRows = from row in dt.AsEnumerable()
let date = DateTime.ParseExact(row.Field<string>("date_purchase"),"dd-mm-yyyy", null)
orderby date
select row;
Sorting a date-column as string also doesn't sort correctly. You should also sort in the database instead of in memory and use parameters instead of string concatenation to prevent sql-injection and date-conversion-issues like this.
string sql = #"SELECT gangId as gang,
respectPoints as respectPoints,
DATE_FORMAT(purchasedDate, '%d-%m-%Y') as date_purchase,
FROM tbl_gang t
WHERE gangId=#gangId
ORDER BY purchasedDate ASC";
using (var cmd = new MySqlCommand(sql, conn))
using (var da = new MySqlDataAdapter(cmd))
{
da.SelectCommand.Parameters.Add("#gangId", MySql.Data.MySqlClient.MySqlDbType.Int32).Value = gangID;
da.Fill(dt); // no need to order this on client side
}

OdbcConnection turns DATE column into STRING?

UPDATE: this happens with OdbcConnection but goes away with SqlConnection. Is there any way to read a "date" via OdbcConnection?
I have a Sql Server database table with a "date" and a "datetime" column. Whenever I use C# ODBC, it returns the Date column as a string. But I would rather it return the Date as a DateTime. Is there any way to make that happen?
string sql = "select dateColumn, dateTimeColumn from Test_Table";
string dsn = "Driver={SQL Server};Server={...};Database=...;Trusted_Connection=True;";
using (OdbcConnection conn = new OdbcConnection(ConfigManager.GetLoansDatabaseDSN()))
{
conn.Open();
OdbcCommand command = new OdbcCommand()
{
Connection = conn,
CommandText = sql
};
using (OdbcDataAdapter adapter = new OdbcDataAdapter(command))
{
DataSet ds = new DataSet();
adapter.Fill(ds);
DataTable table = ds.Tables[0];
//The type of "dateColumn" is now string not DateTime
}
}
One of two ways.
Cast your dateColumn to a DateTime
string sql = "select Convert(DateTime, dateColumn) as dateColumn, dateTimeColumn from Test_Table";
Build your DataTable manually to include the columns type.

Categories