I am Working in ASP.NET and SqlServer.
I have two textboxes with calender extender in my application where user will select two dates.I want to get data between those two dates from sqlserver where my datatype for that particular field is DateTime. please tell me how to proceed with this ...I wrote a query but thats not working..
my query:
SqlCommand cmd = new SqlCommand("select top 1 OrderNumber from tblOrderMaster where OrderedDate>='" + txtfromcal.Text + "' and OrderedDate<='" + txttocal.Text + "' ", conn);
things to do
parameterized the query to prevent from sql injection
use using statement to properly dispose the object
use try-catch block to handle excpetion
eg,
string query = #"select top 1 OrderNumber
from tblOrderMaster
where OrderedDate BETWEEN #startDate AND #endDate";
using(SqlConnection conn = new SqlConnection("connectionString here"))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#startDate", txtfromcal.Text);
cmd.Parameters.AddWithValue("#endDate", txttocal.Text);
try
{
conn.Open();
// other codes
// to fetch the record
}
catch(SqlException e)
{
// do something with
// e.ToString()
}
}
}
SOURCES
AddWithValue Method
Add (recommended method to be used)
use this code:
Sqlcommand cmd=new sql command ("Select data from tablename
where date>=startdate
and date<=enddate",connection)
Try this
SELECT * FROM YourTableName WHERE sqlDateColumnName BETWEEN '" + textbox1.Text + "' AND '" + textbox2.Text + "'
Related
Combobox items binding in database:
using (MySqlConnection connect = new MySqlConnection(connectionString))
{
string sql = "SELECT DISTINCT tedavi_tarih FROM " + mw.db_name + ".tedavi Where hasta_id= '" + mw.hasta_id + "' ORDER BY tedavi_tarih DESC";
using (MySqlCommand cmd = new MySqlCommand(sql, connect))
{
connect.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
combobox_tarih.Items.Add(reader.GetString("tedavi_tarih"));
}
connect.Close();
}
}
tedavi_tarih format is Date but when I add it to combobox, it displays as "5.01.2018 00:00:00". I want to display only "5.01.2018". I tried this in XAML:
ItemStringFormat="dd/M/yyyy"
It doesn't work. How can I fix it?
reader.GetString("tedavi_tarih") returns a string. It doesn't return a DateTime. A string doesn't become a DateTime when you try to convert it to a string using a DateTime format string.
If the "tedavi_tarih" column really is Date, this should work:
while (reader.Read())
{
combobox_tarih.Items.Add(reader.GetDateTime("tedavi_tarih"));
}
If by "format as Date" you really mean that it's a date formatted as a string, you'll have to use DateTime.TryParse(). Let me know.
Obligatory warning: The code below is a SQL injection vulnerability. It is very bad, very dangerous practice. You should not concatenate SQL strings. You should use SqlParameters instead.
string sql = "SELECT DISTINCT tedavi_tarih FROM " + mw.db_name + ".tedavi Where hasta_id= '"
+ mw.hasta_id + "' ORDER BY tedavi_tarih DESC";
I'm trying to use code to insert a row into the database and then immediately display that code after after a button is clicked. I'm using C#.
comm.CommandText = "INSERT INTO Store (FirstName, LastName) Values ('" + txtFirstName.Text + "', '" + txtLastName.Text + "')";
The above code works . But it won't work if I add the following code (which will work instead):
comm.CommandText = "Select FirstName, LastName from Store";
When the button is clicked, I want to insert the row (containing information that was just entered from the textbox) into the table and also display that new row into a form (set up to view the table). I'm trying to get both of the commands to work at the same time, but only the second "Command" works.
Here is what the surrounding code looks like:
protected void btnSubmit_Click(object sender, EventArgs e)
{
String testVar = txtFirstName.Text;
OleDbConnection conn = new OleDbConnection(); //where to find db
conn.ConnectionString = ConfigurationManager.ConnectionStrings["storeConnString"].ConnectionString; //long connection screen.
conn.Open();
OleDbCommand comm = conn.CreateCommand();
comm.Connection = conn;
comm.CommandText = "INSERT INTO Store (FirstName, LastName) Values ('" + txtFirstName.Text + "', '" + txtLastName.Text + "')";
comm.CommandText = "Select FirstName, LastName from Store";
OleDbDataReader reader = comm.ExecuteReader();
(I know I need to use parameters, but I'm going to do that after I figure this out.)
Thanks, Brad
Because after this two lines, your INSERT command will not assigned to your comm anymore.
comm.CommandText = "INSERT INTO Store (FirstName, LastName) Values ('" + txtFirstName.Text + "', '" + txtLastName.Text + "')";
comm.CommandText = "Select FirstName, LastName from Store";
CommandText property only have now your SELECT stament. Just execute your INSERT query with ExecuteNonQuery and after use ExecuteReader to get your SELECT statement result.
comm.CommandText = "INSERT INTO Store (FirstName, LastName) Values ('" + txtFirstName.Text + "', '" + txtLastName.Text + "')";
comm.ExecuteNonQuery();
comm.CommandText = "Select FirstName, LastName from Store";
OleDbDataReader reader = comm.ExecuteReader();
As you said, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
And use using statement to dispose your OleDbConnection, OleDbCommand and OleDbDataReader like;
using(OleDbConnection conn = new OleDbConnection(conString))
using(OleDbCommand comm = conn.CreateCommand())
{
// Execute your INSERT query here.
// Also check your INSERT is successfull or not.
// Assing your SELECT statement to your CommandText property
using(OleDbDataReader reader = comm.ExecuteReader())
{
//
}
}
I am trying to pass parameters from my program to Stored Procedure in EXEC format.Following is my code
public void button1_Click(object sender, EventArgs e)
{
frm = new FrmLogin();
OleDbConnection conn = new OleDbConnection("File Name=E:\\Vivek\\License Manager\\License Manager\\login.udl");
try
{
conn.Open();
string user = username.Text;
string pass = password.Text;
string query = "EXEC dbo.checkuser"' + username.Text'" + " " + "'password.Text'"";
OleDbCommand cmd = new OleDbCommand(query,conn);
cmd.ExecuteNonQuery();
// Retrieve the return value
string result = query.ToString();
MessageBox.Show(result);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn.Close();
}
What should I write in string query=" "?,I am trying to pass username and password as parameters to the stored procedure and once the query executes and returns the result ,I will store it in another variable named result.Am I doing it the right way? I am new to C#
Please suggest,
Thanks
Building command text with dynamically inserted segments from user input is very dangerous, and leaves you open to SQL Injection.
Below is a slight variation which parameterizes those strings. This approach is much safer.
string query = "dbo.checkuser";
OleDbCommand cmd = new OleDbCommand(query,conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#username", username.Text);
cmd.Parameters.AddWithValue("#password", password.Text);
Note: This updated version sets up the command as a stored procedure, instead of plain text.
try this
OleDbCommand cmd = new OleDbCommand("StoredPorcedureName",conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameter.AddWithValue("#user", username.Text);
cmd.Parameter.AddWithValue("#pwd", password.Text);
cmd.ExecuteNonQuery();
That looks Okay at a glance except for your query string. Change to:
string query = "EXEC dbo.checkuser '" + username.Text "', '" + password.Text + "'";
might work better.
Edit
Yes, as per comments about SQL injection, Troy's answer is significantly better.
Just for completeness that can be possibly used in other situations, you can avoid SQL injection using this method by trying something like:
string query = "EXEC dbo.checkuser '" + username.Text.Replace("'", "''") "', '" + password.Text.Replace("'", "''") + "'";
When I log in, I am storing my username in the session. My requirement is that I want to store my username in my database. Here I am storing it in username1. When the username is entered, I can print it using response.write() and it is printing perfectly. However, when I am storing it in the database it is producing this error:
**sqlException was unhandled by user code
and exception at cmd.ExecuteScalar();
String or binary data would be truncated.
The statement has been terminated.**
Following is my ado.net code:
using (SqlConnection con =
new SqlConnection("Data Source=.;database=testdb1;Integrated Security=SSPI")) {
con.Open();
// SqlCommand cmd = new SqlCommand("delete from fileinfo where ID=" + Convert.ToInt32(Request.Params["one"]), con);
string uname = (string) Session["fname"].ToString() + " " + Session["lname"].ToString(); //Session["fname"].ToString()+" "+Session["lname"].ToString();
// Response.Write(uname);
// uname = "sri hari";
uname = uname + " ";
string uname1 = uname;
uname = uname.Trim();
SqlCommand cmd = new SqlCommand("insert into qry_details values('" + txt_query_name.Text + "','pending for approval','" + txt_query_description.Text + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','" + qry + "','" + uname1 + "')", con);
cmd.ExecuteScalar();
}
check the length of qry_details table and see if its smaller than the string you send to the db?
basically the exception says you are trying to something bigger than the column length.
I would recommend you using a parametrized query. Your code is now vulnerable to SQL injection. Also you should use the ExecuteNonQuery method on the SQL command instead of ExecuteScalar when inserting values to the database:
var connectionString = "Data Source=.;database=testdb1;Integrated Security=SSPI";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "INSERT INTO qry_details VALUES (#query_name, 'pending for approval', #query_description, #date, #qry, #username)";
cmd.Parameters.AddWithValue("#query_name", txt_query_name.Text);
cmd.Parameters.AddWithValue("#query_description", txt_query_description.Text);
cmd.Parameters.AddWithValue("#date", DateTime.Now);
cmd.Parameters.AddWithValue("#qry", qry);
cmd.Parameters.AddWithValue("#username", uname1);
cmd.ExecuteNonQuery();
}
This error mostly happen when the inserting value is larger than the field width defined in table on SQL Server.
Check if you are inserting date and time using DateTime.Now c# fuction, your Table must be of type DateTime. not Date or Time only.
I've been trying to get this right for over 2hrs so any help is highly appreciated
public void setAppointment(int studentID, DateTime appt)
{
connection.Open();
string sqlStatement3 = "UPDATE dbo.students SET appointmentDate = '" + appt.Date.ToString("yyyy-MM-dd HH:mm:ss") + "' WHERE ID = " + studentID + ";";
OleDbCommand updateCommand = new OleDbCommand(sqlStatement3, connection);
updateCommand.ExecuteNonQuery();
connection.Close();
}
So basically what that does is insert a datetime into an sql server table keeping the same format of the month and day to avoid regional settings getting in the way.
The only problem is that the time remains 00:00:00. Even though when I debug the code, 'appt' shows 28/06/2013 09:30:00
try below
public void setAppointment(int studentID, DateTime appt)
{
connection.Open();
string sqlStatement3 = "UPDATE dbo.students SET appointmentDate = ? WHERE ID = ?";
OleDbCommand updateCommand = new OleDbCommand(sqlStatement3, connection);
updateCommand.Parameters.AddWithValue("#p1", appt);
updateCommand.Parameters.AddWithValue("#p2", studentID);
updateCommand.ExecuteNonQuery();
connection.Close();
}
BUT!
You say it is sql server but why you using OleDbCommand ?
try below if it is sql server
public void setAppointment(int studentID, DateTime appt)
{
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE dbo.students SET appointmentDate = #appointmentDate WHERE ID = #ID";
con.Open();
cmd.Parameters.AddWithValue("#appointmentDate", appt);
cmd.Parameters.AddWithValue("#ID", studentID);
cmd.ExecuteNonQuery();
}
}
Line 5.
Change
... appt.Date.ToString(...
to
... appt.ToString(...
I hope you have solved your problem from previous post and I agree SQL Statements to be used with parameters.
If you have an application date time format is fixed, then there is no harm in hard-coding but it would be good code to get date time format from your web.config file. This will help your code to be same consistent overall project.
Instead of
ToString("yyyy-MM-dd HH:mm:ss")
ToString(ConfigValue)
Too Late, But for your question : Try the code below.
public void setAppointment(int studentID, DateTime appt)
{
connection.Open();
string sqlStatement3 = "UPDATE dbo.students SET appointmentDate = '" + "CONVERT(datetime, '" + appt.Date.ToString("yyyy-MM-dd HH:mm:ss") + "', 103)" + "' WHERE ID = " + studentID + ";";
OleDbCommand updateCommand = new OleDbCommand(sqlStatement3, connection);
updateCommand.ExecuteNonQuery();
connection.Close();
}