I have a table which I want to insert data in it only once in a day
and to implement that I want to check if current date already exists in
the database by writing these lines
DateTime date = DateTime.Now;
MySqlCommand cmd = new MySqlCommand("SELECT * FROM `attendances` WHERE
`lecture_id` = '" + lecture_id + "' " +
" AND `date` = '"+date.ToShortDateString()+"' ",con);
MySqlDataReader reader = cmd.ExecuteReader();
reader.Read();
if (reader.HasRows)
MessageBox.Show("you can't insert");
else MessageBox.Show("you can insert");
The date is inserted to the database in this format xxxx-xx-xx although using the same method for inserting, and date.ToShortDateString() returns the date in this format
xxxx/x/x .
I checked inserting the date manually in the correct format but that also didn't work, I also tried using the DATE function in sql but that didn't work either.
Just apply format string date = DateTime.Now.ToString("yyyy-MM-dd")
And do not call ToShortDateString() in your SQL query
You also should use SqlParameter as your code is vulnerable for SQL injection attack.
You could also avoid using .NET's DateTime and use MySql's NOW() or UTC_DATE() instead within your query, which may be better; if the region of your code and db reside in different timezones.
i.e.
[...] " AND `date` = DATE(NOW()) ",con);
Related
Simply I have an Excel file and I loaded it into SQL Server 2008.
I want to insert current date into the same cells added from Excel while date transferring... then date inserted automatically every time I added data and never lose old date. How can I do this?
string ssqltable = comboBox1.GetItemText(comboBox1.SelectedItem);
string myexceldataquery = "select * from [" + ssqltable + "$]";
try
{
OleDbConnection oconn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + imagepath + ";Extended Properties='Excel 12.0 Xml; HDR=YES;IMEX=1;';");
string ssqlconnectionstring = "Data Source=.;Initial Catalog=Bioxcell;Integrated Security=true";
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oconn);
oconn.Open();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
DataTable dt = new DataTable();
dt.Load(oledbcmd.ExecuteReader());
bulkcopy.DestinationTableName = ssqltable;
for (int i = 0; i < dt.Columns.Count; i++)
{
bulkcopy.ColumnMappings.Add(i, i);
}
bulkcopy.WriteToServer(dt);
oconn.Close();
}
I used this but I know insert for only last record
I want to insert current date in newly created rows and doesn't lose previous columns date .. for example when i insert data each time insert new date saving old data with old date
SqlCommand Update6 = new SqlCommand("insert into Overseas (Date) Values('" + DateTime.Now.ToShortDateString() + "')", conn);
Update6.ExecuteScalar();
while using
SqlCommand Update6 = new SqlCommand("insert into Overseas (Date) Values (GETDATE())", conn);
Update6.ExecuteNonQuery();
the result was
enter image description here
So what's the solution ?
Set GETDATE() as the default constraint for your Date column of Overseas table.
SQL Command to add constraint:
ALTER TABLE Overseas
ALTER COLUMN Date DATETIME NOT NULL DEFAULT GETDATE()
Post this, you need not pass any value to this column while inserting. Just insert the remaining columns, this will get inserted automatically.
OR
Try this:
SqlCommand Update6 = new SqlCommand("insert into Overseas (Date) Values (GETDATE())", conn);
Update6.ExecuteScalar();
Based on your DB screenshot hope this query helps:
INSERT INTO Overseas (EnglishName,ProductCode,ProductName,TerritoryCode,TerritoryName,Salesvalue,CreditValue,NetSalesValue,Sales,Bonus,Bioxellbricks,BioxellTerritories,Date,ID)
SELECT EnglishName,ProductCode,ProductName,TerritoryCode,TerritoryName,Salesvalue,CreditValue,NetSalesValue,Sales,Bonus,Bioxellbricks,BioxellTerritories,GETDATE(),ID from [exceltablename]
Here Overseas is your DB table and exceltablename is your source table of excel.
You can simply use Datetime.Now(); function to get current date.
Also Use the zzz format specifier to get the timezone offset as hours and minutes. You also want to use the HH format specifier to get the hours in 24 hour format.
DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz")
Result:
2011-08-09T23:49:58+02:00
Some culture settings uses periods instead of colons for time, so you might want to use literal colons instead of time separators:
DateTime.Now.ToString("yyyy-MM-ddTHH':'mm':'sszzz")
Custom Date and Time Format Strings
Hope this will works for you .. Thank you
There is a function GETDATE() for this purpose.
Returns the current database system timestamp as a datetime value
without the database time zone offset. This value is derived from the
operating system of the computer on which the instance of SQL Server
is running.
https://learn.microsoft.com/en-us/sql/t-sql/functions/getdate-transact-sql
I tried to get result depending on two dates which the user checked.
I have two datetimepicker controls.
I want the user to chooses the "from" date and "to" date,
then the query get specific result.
leaving_time column type is nvarchar
This is my query:
SELECT name, mil_no, rotba, arrival_time, leaving_time, day, year
FROM dbo.Hodor_data
WHERE leaving_time BETWEEN '"+dateTimePicker1.Checked.ToString()+ "' AND '" + dateTimePicker2.Checked.ToString() + '"
Where is the mistake?
You should write parameterized queries and not using string concatenation for passing the parameters, in order to create a sql command. Using string concatenation makes you code vulnerable to sql injections.
var cmdText = #"SELECT ...
FROM dbo.Hodor_data
WHERE leaving_time BETWEEN #StartDate AND #EndDate";
var sqlCommand = new SqlCommand(cmdText, connection);
sqlCommand.Parameters.AddWithValue("#StartDate", dateTimePicker1.Value);
sqlCommand.Parameters.AddWithValue("#EndDate", dateTimePicker2.Value);
where connection is your sql connection object.
Try to use dateTimePicker1.Text in dateTimePicker1_ValueChanged event where you are using dateTimePicker2.Checked that return true or false not the value of date
Checked is a boolean property, and it is not the date. You need to use the Value Property. It is better to add parameters and explicitly specify the type so that the date format conflict is solved.
Edit: If column type in SQL server is NVARCHAR and of format MM/dd/yyyy, you need to use ONVERT(DATETIME, leaving_time, 101):
conn.Open();
SqlDataAdapter dataAdapter =
new SqlDataAdapter("SELECT name, mil_no, rotba, arrival_time, leaving_time, day, year "
+ "FROM dbo.Hodor_data where CONVERT(DATETIME, leaving_time, 101) "
+ "BETWEEN #p1 AND #p2", conn);
SqlParameter fromDate = new SqlParameter("#p1", SqlDbType.DateTime2);
fromDate.Value = dateTimePicker1.Value;
SqlParameter toDate = new SqlParameter("#p2", SqlDbType.DateTime2);
toDate.Value = dateTimePicker2.Value;
dataAdapter.SelectCommand.Parameters.Add(fromDate);
dataAdapter.SelectCommand.Parameters.Add(toDate);
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close()
You should really consider changing the type of column leaving_time to be a DateTime column. This will make your life easier in querying. I can't really see any advantage of storing these values as text.
I get Syntax error (missing operator) in query expression
string strSql2 = "Select N_Serie,MacID from " + cmdb_ModelStock2.Text + " WHERE Date_Ajout = " + cmdb_Date2.Text;
I put a break a point and debugg step by step, and I see, it get the date and also the time.
could that be the problem?? If so is it possible to make it get only the date not the time.
The first thing to do is to stop constructing your SQL like that. If you really need to pick the table dynamically, you should make sure you use a whitelist of valid ones... but for the "where" clause you should use parameterized SQL - parse cmdb_Date2.Text into a DateTime, and specify that as the parameter value. Using parameterized SQL protects you from SQL injection attacks, avoids conversion issues, and makes it easier to read your SQL.
So:
string tableName = ValidateTableName(cmdb_ModelStock2.Text); // TODO: Write this!
DateTime date = DateTime.Parse(cmdb_Date2.Text); // See below
string sql = "Select N_Serie,MacID from " + tableName + " WHERE Date_Ajout = ?";
using (var command = new OleDbCommand(sql, conn))
{
// Or use type "Date", perhaps... but that would be more appropriate
// with a range. The name doesn't matter using OLE, which uses positional
// parameters.
command.Parameters.Add("Date", OleDbType.DBDate).Value = date;
// Execute the command etc
}
Note that here I'm using DateTime.Parse, but ideally you'd use a UI control which gives a DateTime directly. (We don't know what kind of UI you're using, which makes it hard to give advice here.)
Depending on what data type you're using in the database, you might want to use a BETWEEN query instead of an exact match.
you better to use parameter for date like below
string strSql2 = "Select N_Serie,MacID from " + cmdb_ModelStock2.Text + " WHERE Date_Ajout = ?";
create date time from your cmdb_Date2, for example if the date time format is "yyyy-MM-dd HH:mm" then
DateTime dt =
DateTime.ParseExact(cmdb_Date2.Text, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
now you can set the parameter value like below
cmd.Parameters.Add("Date_Ajout ", OleDbType.Date).Value = dt;
execute the cmd
I have a MySQL database, there's a table which have column Time's Type is Nvachar(50) and its values is kind like this "05/09/2012 20:53:40:843" *(Month-date-year hour:mins:second:msecond)*
Now I want to query to get a record have Time after "10/05/2012 01:00:30 PM".
I had code in C# to converted it to "05/10/2012 13:00:30" before making a query.
My Query :
SELECT * FROM ABCDFEGH WHERE capTime > '05/10/2012 13:00:30' LIMIT 0, 1
But i got no record. So please tell me how can I can make it return record have time after the time above ???
More Info My C# code :
string tableName = "ABCDFEGH";
string date = "05/10/2012 13:00:30";
var query = "SELECT * FROM " + tableName + " WHERE capTime > '" + date + "' LIMIT 0, 1";
var cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = null;
try
{
dataReader = cmd.ExecuteReader();
}
I'm so so so so so so sorry. I made a mistake the query must be
SELECT * FROM ABCDFEGH WHERE capTime > '05/10/2012 13:00:30' LIMIT 0, 1
This query is successful return the record i need :)
But soemhow I have mistyped it into
SELECT * FROM ABCDFEGH WHERE capTime > '05-10-2012 13:00:30' LIMIT 0, 1
Sorry again, topic close. But tks for evveryone tried :)
I recommend using the DATETIME datatype instead of NVARCHAR. Store dates in YYYY-MM-DD HH:MM:SS format, which is the native DATETIME format recognized by MySQL.
Also use date literals in the same format.
Two reasons for this recommendation: First, DATETIME takes only 8 bytes, instead of up to 150 bytes which is the potential size of a multibyte 50 character varchar.
Second, the sort order of DATETIME will be the same as the chronological order. So if you create an index on the Time column, your > comparison can benefit from the index. Your query will be much faster as a result.
Use TIMESTAMPDIFF()
Schema
CREATE TABLE ABCDFEGH (`right` varchar(3), `time` datetime);
INSERT INTO ABCDFEGH (`right`, `time`)
VALUES
('Yes', '2012-10-02 13:00:30'),
('No', '2012-10-15 13:00:30');
SQL Code
SELECT * FROM ABCDFEGH
WHERE TIMESTAMPDIFF(MINUTE, time, '2012-10-05 13:00:30') > 0
LIMIT 0, 1
Explanation
TIMESTAMPDIFF() returns datetime_expr2 – datetime_expr1, where datetime_expr1 and datetime_expr2 are date or datetime expressions. One expression may be a date and the other a datetime; a date value is treated as a datetime having the time part '00:00:00' where necessary. The unit for the result (an integer) is given by the unit argument.
Fiddle: http://www.sqlfiddle.com/#!2/244cc/1 datetime
Fiddle: http://www.sqlfiddle.com/#!2/063b3/1 varchar(50)
PS1: Time may be a reserved word. Please avoid using it. Else use it with backticks (`).
PS2: The format of time is YYYY-MM-DD not the reverse.
First, why did you save the dates as NVARCHAR? If you are still able to change it to DATETIME datatype and all of the records on it, much better.
But if not, you can use STR_TO_DATE.
SELECT *
FROM tableName
WHERE STR_TO_DATE(`capTime`, '%m/%d/%Y %H:%i:%s:%x') >
STR_TO_DATE('05/10/2012 13:00:30', '%c/%d/%Y %H:%i:%s')
See SQLFiddle Demo
SOURCES
STR_TO_DATE
DATE Formats
UPDATE 1
and your query is vulnerable with SQL Injection. To avoid from it
Parameterized your query
code snippet,
string tableName = "ABCDFEGH";
string date = "05/10/2012 13:00:30";
String query = "SELECT * FROM " + tableName + " WHERE STR_TO_DATE(`capTime`, '%m/%d/%Y %H:%i:%s:%x') > STR_TO_DATE(#dateHere, '%c/%d/%Y %H:%i:%s')";
using (MySqlConnection connection = new MySqlConnection("connectionStringHere"))
{
using (MySqlCommand command = new MySqlCommand())
{
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = query;
command.Parameters.AddwithValue("#dateHere",date)
MySqlDataReader dataReader = null;
try
{
dataReader = cmd.ExecuteReader();
}
catch(MySqlException e)
{
// do something here
// don't suppress the error
}
}
}
I have a query which fetches the information from sql server on datematch.
I have searched a lot about SQL Server date string, I just want to match with the date and get the data from database. Also I am using SQL Server 2005, I want to fetch the date and take the time out of it?
Can anybody help me in that... I am new to C#
Here is my query.
return "select Timein, Timeout from Attendance where E_ID = " + E_ID + " and Date = " + DateTime.Now.ToShortDateString();
use the sql server CONVERT function to convert the input date param to time
Change your query to accommodate any one of the below CONVERT function
SQL query to convert Time format into hh:mm:ss:
select convert(varchar, <<dateparam>>, 108)
SQL query to convert Time format into hh:mi:ss:mmm(24h):
select convert(varchar, <<dateparam>>, 114)
You should always use parameters when querying a database - whether or not SQL injection is possible, it's just plain good practice to use parameters, and it solves some of the thorny how many quotes and which kind do I need here to make it a valid SQL statement questions, too.
So try something like:
string sqlStmt = "SELECT Timein, Timeout FROM dbo.Attendance " +
"WHERE E_ID = #ID AND Date = #Date";
using(SqlConnection conn = new SqlConnection("your-connection-string-here"))
using(SqlCommand cmd = new SqlCommand(sqlStmt, conn))
{
// set up parameters
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = E_ID;
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = DateTime.Now.Date;
// open connection, read data, close connection
conn.Open();
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
// read your data
}
rdr.Close();
}
conn.Close();
}