I'm relatively new to C#, SQL Server, and Stackoverflow.
I want the format of my date to stay the same from SQL Server to my C# code.
I have a screenshot of the SQL Server table:
.
I just want the format to stay the same. I want the format to stay yyyy-mm-dd instead when I retrieve the data the format is dd/mm/yyyy 0:00:00.
I then use the following code to retrieve the data from the server:
ArrayList a = new ArrayList();
DataTable d = new DataTable();
string sql = "SELECT * FROM myServer";
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);
MySqlDataAdapter myA = new MySqlDataAdapter(cmd);
myA.Fill(d);
cmd.ExecuteNonQuery();
foreach (DataRow row in d.Rows)
{
FitnessManager f = new FitnessManager();
f.testDate = row["testDate"].ToString();
f.tDate = row["tDate"].ToString();
f.dtDate = row["dtDate"].ToString();
a.Add(f);
}
return a;
I would expect the results in the ArrayList to be 2020-10-13, instead I'm getting 10/11/2020 0:00:00.
I do not know why this happens for how to fix this.
You would do something like this:
f.tDate = row["tDate"].ToString("yyyy-MM-dd")
The ToString() function accepts a format string, so you can pretty much convert it to whatever format you want.
More information here:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
I found a previous post that helped me out a lot.
Change date format in C# when reading from database and setting to label
I needed to specify that the data being formatted was datatime rather than ToString() being called as an object.
Thanks E.J for putting me on the right track.
Related
In my app, I am trying to grab a date from the database and compare it against local time. Right now I am getting an error when I am converting to date incorrectly.
I have tried:
Convert.ToDateTime()
DateTime.ParseExact()
My code:
string time = "Select top(1) DATE from SERVICE order by DATE desc";
SqlCommand command = new SqlCommand(time, connection);
connection.Open();
using (SqlDataReader timereader = timecommand.ExecuteReader())
{
while (timereader.Read())
{
if (DateTime.ParseExact(time, "yyyy-MM-dd HH:mm:ss", null).AddMinutes(10) > currenttime)
{
// code
}
}
connection.Close();
}
I am hoping when I retrieve this value from the database, I can convert it into a proper datetime value and compare against local time and run other code after that.
At the moment I am just getting this error:
The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.
I'm probably just dumb and missing something obvious..
Your query selects a single value. Use ExecuteScalar and cast it to a DateTime (it's already a DateTime, but boxed inside an object):
string time = "Select top(1) DATE from SERVICE order by DATE desc";
SqlCommand command = new SqlCommand(time, connection);
connection.Open();
DateTime d = (DateTime)command.ExecuteScalar();
connection.Close();
After you do this, and before you embark on some long mission of this protracted way of getting data out of a database, converting it to objects for use in your app etc, take a look at least at an ORM called Dapper, if not Entity Framework. Dapper's basically what you're doing now, but it auto converts your queries to objects and back and saves a lot of tedious code. With Dapper it'd look more like:
using (var connection = new SqlConnection("connstr"))
{
var d = connection.QuerySingle<DateTime>("SELECT TOP 1 Date FROM ...");
}
Yes, it's not much of a saving over what you have now, right? But what if you have a list of Order that themselves have 20 properties:
using (var connection = new SqlConnection("connstr"))
{
var orders = connection.Query<Order>("SELECT * FROM order WHERE customerID = #custid", new {custid = 123}).ToList();
}
Orders is now a list of Order objects for customer 123, parameterized, injection safe, quick and a one liner to read and populate your orders; doing that in a datareader is going to take at least 25 lines of boring code
http://dapper-tutorial.net and spend 2 minutes reading; I'll lay bets you'll be glad you did
Just try to read the value as a proper, native DateTime type like this (assuming that the DATE column in SQL Server is in fact a DATETIME or similar datatype - not a string - hopefully!):
using (SqlDataReader timereader = timecommand.ExecuteReader())
{
while (timereader.Read())
{
// just read the DateTime value as such
DateTime dt = timereader.GetDateTime(0);
// then do whatever you need to do with this DateTime value .....
}
connection.Close();
}
When selecting data from the database and the condition is date, I receive this message that there is a data type mismatch in the criteria expression.
This is my code.
public DataTable loadhooodor()
{
DataTable hooodorDt = new DataTable();
OleDbDataAdapter hooodorDa;
hooodorDt.Clear();
DateTime today = new DateTime();
today = DateTime.Today;
hooodorDa = new OleDbDataAdapter("select * from HoodoorEnseraf where heDate='"+ today+ "'", connection);
hooodorDa.Fill(hooodorDt);
return hooodorDt;
}
and
private void dataGridRefresh()
{
dataGridView1.DataSource = null;
dataGridView1.Update();
dataGridView1.Refresh();
dataGridView1.DataSource = loadhooodor();
}
I receive this message.
My access data table is,
That's one of the problems with not using parametrized queries. Try this instead
hooodorDa = new OleDbDataAdapter("select * from HoodoorEnseraf where heDate=#today", connection);
hooodorDa.SelectCommand.Parameters.Add("#today",
System.Data.SqlDbType.DateTime);
hooodorDa.SelectCommand.Parameters["#today"].Value = today;
hooodorDa.Fill(hooodorDt);
When you refer to a date in Access you have to put # around it. This link gives more details
You will also want to make sure your date is formatted correctly. You can use ToString for this.
So your code becomes:
hooodorDa = new OleDbDataAdapter("select * from HoodoorEnseraf where heDate=#"+ today.ToString("yyyy/MM/dd")+ "#", connection);
check the date format of your system & the date format of the date you are sending in.
I am making something that requires MySQL. I have the saving done from in-game, which is simply done by INSERT.
I have a column that will have a password in and I need to check if the inputted password matched any of the rows and then if it is, get all of the contents of the row then save it to variables.
Does anyone have an idea how to do this in C#?
//////////////////////////
I have found how to save and get the string, however it will only get 1 string at a time :(
MySql.Data.MySqlClient.MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT * FROM (player) WHERE (pass)";
command.ExecuteNonQuery();
command.CommandType = System.Data.CommandType.Text;
MySql.Data.MySqlClient.MySqlDataReader reader = command.ExecuteReader();
reader.Read();
ayy = reader.GetString(1);
print (ayy);
if(ayy == password){
//something
}
My best practice is to use MySQLDataAdapter to fill a DataTable. You can then iterate through the rows and try to match the password.
Something like this;
DataTable dt = new DataTable();
using(MySQLDataAdapter adapter = new MySQLDataAdaper(query, connection))
{
adapter.Fill(dt);
}
foreach(DataRow row in dt.Rows)
{
//Supposing you stored your password in a stringfield in your database
if((row.Field<String>("columnName").Equals("password"))
{
//Do something with it
}
}
I hope this compiles since I typed this from my phone. You can find a nice explanation and example here.
However, if you are needing data from a specific user, why not specificly ask it from the database? Your query would be like;
SELECT * FROM usercolumn WHERE user_id = input_id AND pass = input_pass
Since I suppose every user is unique, you will now get the data from the specific user, meaning you should not have to check for passwords anymore.
For the SQL statement, you should be able to search your database as follows and get only the entry you need back from it.
"SELECT * FROM table_name WHERE column_name LIKE input_string"
If input_string contains any of the special characters for SQL string comparison (% and _, I believe) you'll just have to escape them which can be done quite simply with regex. As I said in the comments, it's been a while since I've done SQL, but there's plenty of resources online for perfecting that query.
This should then return the entire row, and if I'm thinking correctly you should be able to then put the entire row into an array of objects all at once, or simply read them string by string and convert to values as needed using one of the Convert methods, as found here: http://msdn.microsoft.com/en-us/library/system.convert(v=vs.110).aspx
Edit as per Prix's comment: Data entered into the MySQL table should not need conversion.
Example to get an integer:
string x = [...];
[...]
var y = Convert.ToInt32(x);
If you're able to get them into object arrays, that works as well.
object[] obj = [...];
[...]
var x0 = Convert.To[...](obj[0]);
var x1 = Convert.To[...](obj[1]);
Etcetera.
string sqlUserName3 = "SELECT out_date FROM status where s_id='" + TextBox2.Text + "'";
SqlCommand sqlcmd3 = new SqlCommand(sqlUserName3, sqlcon);
sqlUserName4 = "SELECT in_date FROM status where s_id='"+TextBox2.Text+"'";
SqlCommand sqlcmd4 = new SqlCommand(sqlUserName4, sqlcon);
string q3 = sqlcmd3.ExecuteNonQuery().ToString();
string q4 = sqlcmd4.ExecuteNonQuery().ToString();
DateTime dt1 = DateTime.Parse(q3);
DateTime dt2 = DateTime.Parse(q4);
TimeSpan result = dt1.Subtract(dt2);
string result1 = result.ToString();
TextBox8.Text = result1;
//Response.Redirect("login.aspx");
sqlcon.Close();
There are many things wrong with your code at the moment:
You shouldn't use string concatenation to build your query. Use parameterized SQL instead. This will avoid SQL injection attacks and conversion issues
You're using ExecuteNonQuery when you're trying to execute... a query.
You're converting the results into a string which is a bad idea even if it did return a date... instead, get the results in a form you can fetch as just a DateTime. Avoid string conversions wherever you can.
So you should:
Use parameters instead of dynamic SQL
Use ExecuteReader and get the first result from each reader
Use the GetDateTime method to get the DateTime from the results.
I would personally use the subtraction operator afterwards, too:
TimeSpan difference = end - start;
... but that's just a matter of preference, and not an actual mistake in your current code.
Your mistake is here:
string q3 = sqlcmd3.ExecuteNonQuery().ToString();
string q4 = sqlcmd4.ExecuteNonQuery().ToString();
DateTime dt1 = DateTime.Parse(q3);
DateTime dt2 = DateTime.Parse(q4);
ExecuteNonQuery does not return a date in a string representation. It returns the number of records affected by the query; hence, when you run DateTime.Parse(number) you get an error.
None of your queries are returning a date so it's unclear how you expect to get a date back from calling the SQL you have in your question...
Update
Do not use string concatenation to build your SQL Statements. You can use parameters to avoid exposing yourself to SQL Injection attacks. One example would be:
string sqlUserName3 = "SELECT out_date FROM status where s_id=#id";
SqlCommand sqlcmd3 = new SqlCommand(sqlUserName3, sqlcon);
sqlcmd3.Parameters.AddWithValue("#id",TextBox2.Text );
You use SqlCommand.ExecuteNonQuery() but you need SqlCommand.ExecuteScalar(). The first function returns nothing, it's supposed to be used for queries like insert or update. The second returns value of first cell of first row of query output.
You should use execute scalar or pass some out parameter to get value. This should get you some value in q3 and q4.
Now to avoid erros you should also use DateTime.ParseExact instead of simple Parse.
DateTime dt1 = DateTime.ParseExact(q3,"dd/mm/yyyy HH:mm",CultureInfo.InvariantCulture);
DateTime dt2 = DateTime.ParseExact(q4,"dd/mm/yyyy HH:mm",CultureInfo.InvariantCulture);
I have data stored in a SQL database that I'm attempting to read into an ASP.NET MVC application. I can get the data just fine - but the datetimes are not translating into anything useful.
Here's what I have so far (some data redacted as "..."):
public JsonResult GetXYZByStatusJson()
{
var sqlConn = new SqlConnection(...);
var command = new SqlCommand("...", sqlConn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#status", 0);
sqlConn.Open();
var sqlResult = command.ExecuteReader();
var collection = new Collection<Object>();
while (sqlResult.Read())
{
collection.Add(new XYZ(
...
Convert.ToDateTime(sqlResult["DateSent"]),
Convert.ToDateTime(sqlResult["DateDue"]),
...
));
}
sqlResult.Close();
sqlConn.Close();
return Json(collection);
}
The resulting JSON is formatted fine, but the dates look like "\/Date(1294120800000)\/"
How do I properly cast the SQL datetime into a C# DateTime? Using .ToString() doesn't have any affect.
There are nothing wrong with the conversion between Sql Server and C#.
The problem is how JsonResult formats the string.
The following SO question shows how you can process it at client side: How do I format a Microsoft JSON date?
The other way is to create your own alternative to JsonResult
If it is SQL Server, sqlResult["DateSent"].ToString() will give you something like this:
"6/9/1999 12:00:00 AM, 8/15/1999 12:00:00 AM"
Use the built-in string methods (.IndexOf(), .Remove(), etc), or create your own, to parse whatever you need out of this string.