It is possible to auto-increment datetime which I parse from daterangepicker to add AddDays(7) and then insert it to DB?
string strValue = Page.Request.Form["daterange"];
string strValue2 = Page.Request.Form["daterange2"];
DateTime myDate = DateTime.Parse(strValue);
DateTime myDate2 = DateTime.Parse(strValue2);
queryStr = "INSERT INTO `wp_reservations` ( `arrival`, `departure`, `user`, `name`, `email`, `country`, `approve`, `room`, `roomnumber`, `number`, `childs`, `price`, `custom`, `customp`, `reservated`) VALUES ('" + strValue + "INTERVAL 7 DAY', '" + strValue2 + "', 0, '" + DropDownList1.SelectedItem.Text + "', '" + emailValue + "', 'SI', '" + DropDownList2.SelectedValue + "', '" + DropDownList3.SelectedValue + "', '1', 10, 0, '0;0', '', '', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss tt") + "');";
You can use
DATE_ADD(NOW(), INTERVAL 7 DAY) in insert query
If u want to do this in code see Datetime in C# add days
U can also do it in DAO query see DATEADD (Transact-SQL)
Related
//I have this code and I want to insert only the date in the database without //the time, but this will always store value like this: 2019-10-19 00:00:00.000.
SqlCommand cmd2 = conn.CreateCommand();
cmd2.CommandType = CommandType.Text;
DateTime date = DateTime.ParseExact(TextBox_DepartureDate.Text, "dd/MM/yyyy", null);
DateTime date2 = DateTime.ParseExact(TextBox_ArrivalDate.Text, "dd/MM/yyyy", null);
string time1 = TextBox_DepartureTime.Text + " " + DropDownListAMPM.SelectedValue;
string time2 = TextBox_ArrivalTime.Text + " " + DropDownList_AMPM2.SelectedValue;
DateTime dateOnly1 = date.Date;
DateTime dateOnly2 = date2.Date;
if (date <= DateTime.Now.Date)
{
Label_EditTableMessage.ForeColor = System.Drawing.Color.Red;
Label_EditTableMessage.Text = "Departure Date Cannot be in the past";
}
else
{
if (date2 <= date)
{
Label_EditTableMessage.ForeColor = System.Drawing.Color.Red;
Label_EditTableMessage.Text = "Return Date Cannot be Less than the Departure Date";
}
else
{
cmd2.CommandText = "insert into flight(airline_id,flight_number,numer_seats,departure_city,destination_city,departure_time,arrival_time,departure_date,arrival_date) values( '" + DropDownList_AirlineId.SelectedValue + "','" + TextBox_FlightNumber.Text + "','" + TextBox_NumerSeats.Text + "', '" + TextBox_DepartureCity.Text + "', '" + TextBox_DestinationCity.Text + "', '" + time1 + "', '" + time2 + "', '" + dateOnly1 + "', '" + dateOnly2 + "') ";
cmd2.ExecuteNonQuery();
Label_EditTableMessage.ForeColor = System.Drawing.Color.Green;
Label_EditTableMessage.Text = "Flight Added";
EmptyTextBoxes();
GridView_Flight.DataBind();
}
}
}
The problem is not with your code. You should change the data type of your field in the database. Instead of datetime or datetime2 you should use date.
You can refer to this article: https://learn.microsoft.com/en-us/sql/t-sql/functions/date-and-time-data-types-and-functions-transact-sql?view=sql-server-ver15#DateandTimeRelatedTopics
2 parts to this:
Your schema probably has the column data type set to DATETIME instead of just DATE which is going to cause it to store the full date and time regardless. This is the first thing I would check.
In your C# you can use the .Date property on a DateTime object to get just the date part of it. This is irrelevant if you use the correct data type for your column as per point 1
date.Date
or if you want it in string format:
date.Date.ToShortDateString()
the problem is you use
DateTime dateOnly1 = date.Date;
DateTime dateOnly2 = date2.Date;
and previus you use
DateTime date = DateTime.ParseExact(TextBox_DepartureDate.Text, "dd/MM/yyyy", null);
DateTime date2 = DateTime.ParseExact(TextBox_ArrivalDate.Text, "dd/MM/yyyy", null);
you are working only with date, and the datetime assume the time with 00:00:00
I have a SQL statement for querying in MS Access. I want to get the result of the transaction between dates.
This is my code:
DateTime pFromNew = Convert.ToDateTime(this.dateTimePicker1.Value.ToString("yyyy-MM-dd"));
DateTime pToNew = Convert.ToDateTime(this.dateTimePicker2.Value.ToString("yyyy-MM-dd"));
string pFrom = "#" + pFromNew.ToString() + "#";
string pTo = "#" + pToNew.ToString() + "#";
chrTrans.Series["Class"].Points.Clear();
oconn.Open();
OleDbCommand cmd = oconn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select ClassType,Nametree,TransWeight,Valuedate from tblTrans where Nametree = '" + this.cboNametree.Text.Trim() + "' and valuedate between '" + pFrom + "' and '" + pTo + "'";
//+ "' and valuedate between '"+ this.dateTimePicker1.Text +"' and '"+ this.dateTimePicker2.Text +"'";
cmd.ExecuteNonQuery();
What is wrong with this statement?
I always get this error:
DATA Type mismatch in criteria expression.
Remove the single quotes you have in your string... I will show you...
This line:
cmd.CommandText = "Select ClassType,Nametree,TransWeight,Valuedate from tblTrans where Nametree = '" + this.cboNametree.Text.Trim() + "' and valuedate between '" + pFrom + "' and '" + pTo + "'";
Should be:
cmd.CommandText = "Select ClassType,Nametree,TransWeight,Valuedate from tblTrans where Nametree = '" + this.cboNametree.Text.Trim() + "' and valuedate between " + pFrom + " and " + pTo;
The reason is that you already concatenated a # symbol around your date strings--and the single quote thus is not needed.
You are making this too complicated, converting back and forth three times.
It can be reduced to:
string pFrom = "#" + this.dateTimePicker1.Value.ToString("yyyy'/'MM'/'dd") + "#";
string pTo = "#" + this.dateTimePicker2.Value.ToString("yyyy'/'MM'/'dd") + "#";
// snip
cmd.CommandText = "Select ClassType,Nametree,TransWeight,Valuedate from tblTrans where Nametree = '" + this.cboNametree.Text.Trim() + "' and valuedate between " + pFrom + " and " + pTo + "";
I'm trying to write to a database and am getting the "Input String Was Not In Correct Format" error. I'm assuming it's the data types on the last two columns but I'm not sure how to change. In SQL Server, they are both of the money datatype. Code below:
string query = null;
for (int i = 0; i < result.Tables[0].Rows.Count; i++)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
query = "INSERT INTO Upload(Email, TimeStamp, EmployeeId, Name, Title, Department, Race, Gender, AnnualizedBase, AnnualizedTCC) VALUES ('"
+ System.Web.HttpContext.Current.User.Identity.GetUserId() + "', "
+ " '" + DateTime.Now + "', "
+ " '" + result.Tables[0].Rows[i][0].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][1].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][2].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][3].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][4].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][5].ToString() + "', "
+ Convert.ToInt32(result.Tables[0].Rows[i][6]) + ", "
+ Convert.ToInt32(result.Tables[0].Rows[i][7])
+ ")";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
}
The error Input string was not in correct format is most likely caused by one of the values in your column not being convertible to an int. If the datatype in SQL is money then you should try and convert to a decimal and not an int. Try this for each row:
decimal num;
if (decimal.TryParse(result.Tables[0].Rows[i][6], out num))
{
// use num because it is indeed a decimal (money in SQL)
}
else
{
// What do you want to do? Log it and continue to next row?
}
Also please read Bobby Tales and example of paratmetrized query.
This question already has answers here:
What are good ways to prevent SQL injection? [duplicate]
(4 answers)
How can I add user-supplied input to an SQL statement?
(2 answers)
Closed 5 years ago.
Here is my code and I am getting insert error.
Kindly help
OleDbConnection cnn = new OleDbConnection(dbConnection);
cnn.Open();
OleDbCommand cmd = cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO [Emp Data] (" +
"EmpID, Active, EmpName, DOJ, DOL, [Next Manager], DOB, Department, Section, Designation, [Father Name], Address, Town, CNIC, Education, [Habib Metro], [Salary PM], EmailID, [JS Bank Account], [Salary on joining], [Last inc Rs], [Last inc Date], [Next of Kin Name], Relation, [Contact No], Comments, [Reason of Leaving], DOC, [Shift Timings], [Off Day 1], [Off Day 2]"
+ ") VALUES (" +
id + ", 'A' , '" + name + "', '" + doj + "', null '" + manager + "', '" + dob + "', '" + dept + "', '" + section + "', '" + desg + "', '" + father + "', '" + add + "', '" + town + "', '" + cnic + "', '" + education + "', '" + metroBank + "', " + salaryPM + ", '" + email + "', '" + jsBank + "', " + salary + ", 0, 0, null, '" + kinName + "', '" + kinRelation + "', '" + kinContact + "', '" + comments + "', null '" + doc + "', '" + shift + "', '" + offDay1 + "', '" + offDay2
+ "');";
cmd.ExecuteNonQuery();
cnn.Close();
I suspect:
null '"
should be:
null, '"
You are missing a comma in a couple of places.
i have another question for anyone willing to help. This should be fairly easy but for whatever reason i cant seem to get it right. Im working with visual studio 08 creating a asp.net website in c#
im trying to have a user register, which is all working great, and have the new user default as a user and not a admin. I am using a .MDB as where everything is stored.
is it possible to do this in my initial sql query?
currently my code looks like
strSQL = "Insert into tblUserLogin " +
"(UserFirstName, UserLastName, UserName, UserPassword, UserAddress, UserCity, UserState, UserZipCode, UserEmail, UserPhone, ) values ('" +
UserFirstName + "', '" + UserLastName + "', '" + UserName + "', '" + UserPassword + "', '" + UserAddress +
"', '" + UserCity + "', '" + UserState + "', '" + UserZipCode + "', '" + UserEmail + "', '" + UserPhone +
"')";
// set the command text of the command object
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// Execute the insert statement
command.ExecuteNonQuery();
this will successfully post everything to the .MDB and it will leave the cell under the column SecurityLevel empty.
i attempted to add
"(UserFirstName, UserLastName, UserName, UserPassword, UserAddress, UserCity, UserState, UserZipCode, UserEmail, UserPhone, SecurityLevel=U )
but this did not work as i hoped it would. Is there a simple way to have that value SecurityLevel default to U without anyone having to specify it?
thank you for your time
If I understand you correctly just use a const value 'U' for SecurityLevel column
strSQL = "INSERT INTO tblUserLogin " +
"(UserFirstName, UserLastName, " +
" UserName, UserPassword, " +
" UserAddress, UserCity, " +
" UserState, UserZipCode, " +
" UserEmail, UserPhone, SecurityLevel) " +
"VALUES (" +
UserFirstName + "', '" + UserLastName + "', '" +
UserName + "', '" + UserPassword + "', '" +
UserAddress + "', '" + UserCity + "', '" +
UserState + "', '" + UserZipCode + "', '" +
UserEmail + "', '" + UserPhone + "', 'U')"; // pass a const value for SecurityLevel column
// the rest of your code goes here
On a side note: Your code is vulnerable to sql-injections. Learn and use prepared (parameterized) statements instead of dynamically building a query strings.