error Sql query with datetime - asp.net

I got a error when I do the follow:
DateFrom has as datatype of datetime
My C# code:
string strQuery = "Select * FROM Agenda Where DateFrom='" + Calendar1.SelectedDate.Date.Date + "' ";
SqlCommand command = new SqlCommand(strQuery, Global.myConn);
da = new SqlDataAdapter(command);
da.Fill(Global.dsAgenda, "Tabel");
ddlActivity.DataSource = Global.dtAgenda;
ddlActivity.DataBind();
Calendar1 type:
Error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

You should prefer using parameters:
string strQuery = "SELECT * FROM Agenda WHERE DateFrom = #Date";
SqlCommand command = new SqlCommand(strQuery, Global.myConn);
command.Parameters.Add("#Date", SqlDbType.DateTime).Value = Calendar1.SelectedDate;

Use this
Convert(DateTime,Calendar1.SelectedDate.Date.Date,103)

Related

Error: An expression of non-boolean type specified in a context where a condition is expected

I want to pass three query string variables, which ars DateFrom, DateTo and UserName. When I call that the variable, it shows an error:
'An expression of non-boolean type specified in a context where a condition is expected, near 'admin'.'".
How can I resolve the issue? Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
strDate = Convert.ToDateTime(Request.QueryString["DateFrom"]);
endDate = Convert.ToDateTime(Request.QueryString["DateTo"]);
UserName = Convert.ToSingle(Request.QueryString["UsName"]);
string UserName = Request.QueryString["UsrName"];
string sql;
sql = ("SELECT * FROM tblReport WHERE Date between'" + strDate + "'and'" + endDate + "'and'" + UserName + "'");
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
DataTable dt = new DataTable();
DataSet dst = new DataSet();
sda.Fill(dst, "tblReport");
crypt.Load(#"D:\My Project\Asp.Net\ITApplication\ITApplication\CrystalReport.rpt");
crypt.SetDataSource(dst);
CrystalReportViewer1.ReportSource = crypt;
}
you are missing something in your where clause... should be like this:
WHERE Date BETWEEN '<FromDate>' AND '<ToDate>'
AND UserName = '<UserName>'
Your SQL string is not formatted well.
Put spaces near yout and operators and use () in your between:
sql = ("SELECT * FROM tblReport WHERE [Date] between ('" + strDate + "' and '" + endDate + "') and UserName='" + UserName + "'");
Side note:
Using SQL strings with concatenating values like this is a very bad idea. It exposes you to SQL Injections, and overall a bad practice. Please consider using Command.Parameters:
SqlCommand Command = new SqlCommand("SELECT * FROM tblReport WHERE [Date] between (#strDate and #endDate) and UserName=#UserName");
Command.Parameters.Add(new SqlParameter("strDate", strDate));
Command.Parameters.Add(new SqlParameter("endDate", endDate));
Command.Parameters.Add(new SqlParameter("UserName", UserName));

Conversion failed

I want to add some parameter to a table and I get this error in the Visual Studio 2013. I'm having trouble with Date & Time. My date & time datatypes used in SQL Server 2008 R2 are Date and Time(7). I get this error
Conversion failed when converting date and/or time from character string
What is my mistake?
My code:
string strquery = "select count(*) from SaloonGeneralReservation where SaloonReservationDate=#SaloonReservationDate";
SqlConnection connection2 = DBConnection.getConnection();
connection2.Open();
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = connection2;
cmd2.CommandText = strquery;
cmd2.Parameters.Add("#SaloonReservationDate", txt1_date.Text);
int intRowCount = (int) cmd2.ExecuteScalar();
txt1_date.Text = intRowCount.ToString();
connection2.Close();
if (intRowCount == 1)
{
Messages myMsg = new Messages(); // ایجاد نمونه از کلاس
myMsg.CreateMessageAlert("سالن در این تاریخ رزرو شده است . لطفا تاریخ دیگری وارد نمایید.");
txt1_date.Text = "";
}
else
{
string strQuery = "INSERT INTO [WeedingSalonGeneralRes](Date,Time,Fruit,Drink,Desert,MainFood,Salad,TableFlower,SaloonLighting,Saloondesign,SloonCrew,Pastry,GiftCard,customer_id)" + "VALUES(#Date,#Time,#Fruit,#Drink,#Desert,#MainFood,#Salad,#TableFlower,#SaloonLighting,#Saloondesign,#SloonCrew,#Pastry,#GiftCard,#customer_id)";
SqlConnection connection = DBConnection.getConnection();
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = strQuery;
string cis = Session["customerID"].ToString();
cmd.Parameters.Add("#Date", txt1_date.Text);
cmd.Parameters.Add("#Time", txt2_time.Text);
cmd.Parameters.Add("#Fruit", fruit);
cmd.Parameters.Add("#Drink", drink);
cmd.Parameters.Add("#Desert", desert);
cmd.Parameters.Add("#MainFood", mainfood);
cmd.Parameters.Add("#Salad", salad);
cmd.Parameters.Add("#TableFlower", tableflower);
cmd.Parameters.Add("#SaloonLighting", saloonlighting);
cmd.Parameters.Add("#Saloondesign", saloondesing);
cmd.Parameters.Add("#SloonCrew", salooncrew);
cmd.Parameters.Add("#Pastry", pastry);
cmd.Parameters.Add("#GiftCard", giftcard);
cmd.Parameters.Add("#customer_id", cis);
cmd.ExecuteNonQuery();
connection.Close();
Response.Redirect("ReservationSucces.aspx");
}
Your TIME(7) needs to be HH:MM:SS at a minimum, and HH:MM:SS.NNNNNNN maximum. So, add :00 on your string for your TIME to make the conversion work. The DATE should be fine as long as you are using YYYY-MM-DD. You WILL get this error if you are using YYYY-DD-MM.

Fetching Data from database as per details

string date = ddlShowDates.SelectedValue.ToString();
cmd = new SqlCommand("SELECT tbl_Shows.ShowTime FROM tbl_Shows INNER JOIN tbl_MovieTimings ON tbl_Shows.ShowId = tbl_MovieTimings.ShowId WHERE tbl_MovieTimings.Date='" + date + "'", con);
I want to display show time in dropdownlist as per date is selected.
Always use sql-parameters instead of string concatenation to prevent sql-injection.
I guess you have a second DropDownList which should be filled from the first:
DateTime date = DateTime.Parse(ddlShowDates.SelectedValue);
string sql = #"SELECT tbl_Shows.ShowTime
FROM tbl_Shows
INNER JOIN tbl_MovieTimings
ON tbl_Shows.ShowId = tbl_MovieTimings.ShowId
WHERE tbl_MovieTimings.Date=#Date";
using(var con = new SqlConnection("ConnectionString"))
using(var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#Date", SqlDbType.Date).Value = date;
con.Open();
using(var rd = cmd.ExecuteReader())
{
while(rd.Read())
{
TimeSpan time = rd.GetTimeSpan(0);
timeDropDownList.Items.Add(time.ToString());// change format as desired in TimeSpan.ToString
}
}
}

Conversion failed when converting datetime from character string ASP.NET

I get a Conversion failed error when converting DateTime from character string, any help?
sqlcon.Open();
sqlcmd = new SqlCommand("select [Uzsak_Nr],[Preke],[Uzsak_Kiekis],[Gaut_Kiekis],[MyDate],[Gaut_Data] from emp where MyDate between '" + TextBoxData1 + "' and '" + TextBoxData2 + "' ", sqlcon);
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
GridViewRodyti.DataSource = dt;
GridViewRodyti.DataBind();
sqlcon.Close();
This has got SQL Injection written all over it...
Use parameterized queries e.g.
var sqlCmd = new SqlCommand("select [Uzsak_Nr],[Preke],[Uzsak_Kiekis],[Gaut_Kiekis],[MyDate],[Gaut_Data] from emp where MyDate between '#startDate' and '#endDate'", sqlcon);
sqlCmd.Parameters.Add(new SqlParameter("#startDate", DateTime.Parse(TextBoxData1)));
sqlCmd.Parameters.Add(new SqlParameter("#endDate", DateTime.Parse(TextBoxData2)));
Your issue is probably due to an invalid date format, if you use SqlParameter and convert the string to a DateTime it should take care of the conversion for you.
I would advise you do it like this...
sqlcon.Open();
DateTime date1;
DateTime date2;
DateTime.TryParse(TextBoxData1.Text, out date1); //is TextBoxData1 a TextBox?
DateTime.TryParse(TextBoxData2.Text, out date2);
if (date1 != null && date2 != null) {
sqlcmd = new SqlCommand(
"select [Uzsak_Nr],[Preke],[Uzsak_Kiekis],[Gaut_Kiekis],[MyDate],[Gaut_Data] " +
"from emp where MyDate between #dt1 and #dt2 ", sqlcon);
sqlcmd.Parameters.AddWithValue("#dt1", date1);
sqlcmd.Parameters.AddWithValue("#dt2", date2);
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
GridViewRodyti.DataSource = dt;
GridViewRodyti.DataBind();
sqlcon.Close();
}
Using parameterised queries is much nicer and doesn't run the risk of injection.
I have assumed you are using SQLServer.

Refuses to make ExecuteNonQuery : Incorrect syntax near '('

Im trying to insert data to my database, and it gives me an error :
Incorrect syntax near '('.
This is my code :
string username = Session["Session"].ToString();
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
con.Open();
string knowWhichOne = "SELECT ID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
SqlCommand comm = new SqlCommand(knowWhichOne, con);
int userID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT ClassID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int classID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT SchoolID FROM Users WHERE Username='"+UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int schoolID = (Int32)comm.ExecuteScalar();
if (RadioWords.Checked == true)
{
game = 1;
}
else
{
game = 2;
}
string sqlqueryString = "INSERT INTO (GameID, UserID, LengthOfArray, NumberOfErrors, ClassID, SchoolID) VALUES (#GameID, #UserID, #LengthOfArray, #NumberOfErrors, #ClassID, #SchoolID)";
SqlCommand commandquery = new SqlCommand(sqlqueryString, con);
commandquery.Parameters.AddWithValue("GameID", game);
commandquery.Parameters.AddWithValue("UserID", userID);
commandquery.Parameters.AddWithValue("LengthOfArray", HowMany.Text);
commandquery.Parameters.AddWithValue("NumberOfErrors", 0);
commandquery.Parameters.AddWithValue("ClassID", classID);
commandquery.Parameters.AddWithValue("SchoolID", schoolID);
commandquery.ExecuteNonQuery();
con.Close();
I run it in debug mode, and its accepting everything until the "ExecuteNonQuery();" line.
anybody has a clue what I did wrong?
Thanks!
you did this:
INSERT INTO (GameID....
but should do this:
INSERT INTO tablename (GameID....
Your INSERT INTO statement is missing the name of the table into which it is supposed to insert.
The syntax of your insert into statement is incorrect as you are not specifying which table you are inserting into.
The correct syntax is
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
See : http://www.w3schools.com/sql/sql_insert.asp for more information

Resources