Below is my sql query written in APP.Config
<add key="query" value="Select *
from POManage po
Where po.VendorID = #manufacturerid
and po.order_date between #StartDate and #EndDate order by PONumber asc"/>
Here is my Program .cs code
int manufacturerid = 32;
DateTime StartDate = DateTime.Now.AddDays(-1);
DateTime EndDate = DateTime.Now;
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add("#manufacturerid", SqlDbType.BigInt,manufacturerid);
cmd.Parameters.AddWithValue("#StartDate", StartDate);
cmd.Parameters.AddWithValue("#EndDate", EndDate);
cmd.CommandType = CommandType.Text;
SqlDataAdapter ad = new SqlDataAdapter(query, con);
ad.Fill(ds);
But it is showing error for #manufacturerid Must declare the scalar variable.
Similar issue is coming for StartDate and EndDate.
firstly, It's a very bad idea to keep the command query in the appconfig
You have already created a command with query. You need pass the command to Adapter. not query.
int manufacturerid = 32;
StartDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
EndDate = DateTime.Now.ToString("yyyy-MM-dd");
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add("#manufacturerid", SqlDbType.BigInt,manufacturerid);
cmd.Parameters.AddWithValue("#StartDate", StartDate);
cmd.Parameters.AddWithValue("#EndDate", EndDate);
cmd.CommandType = CommandType.Text;
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(ds);
and change Where po.VendorID = '#manufacturerid' to Where po.VendorID = #manufacturerid in your query
update:
int manufacturerid = 32;
var query = #"Select * from POManage po
Where po.VendorID = #manufacturerid
and CONVERT(DATE, po.order_date) between #StartDate and #EndDate
order by PONumber asc";
var startDate = DateTime.Now.AddDays(-1);
var endDate = DateTime.Now;
var connectionString = "your connection string";
var dataTable = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(query, con))
{
adapter.SelectCommand.Parameters.AddWithValue("#manufacturerid", manufacturerid);
adapter.SelectCommand.Parameters.AddWithValue("#StartDate", startDate);
adapter.SelectCommand.Parameters.AddWithValue("#EndDate", endDate);
adapter.Fill(dataTable);
}
}
Related
From the C# code, I am trying to execute a query and pass two parmeters to Access database. Unforunately the parameter name is same beacuse I am passing date parameter. It seems when i exceute the code the first parametr is replaced by the second parameter so for e.g I am passing
Startdate as 1/1/2017 and end date as 1/31/2017
I am still getting the 2016 values.
Below is my code
string ConnString = getConnstring();
string DirectoryPath = getDirectortyPath(year, quater);
StreamWriter file = new StreamWriter(DirectoryPath);
string StartDate = calculateStartDate(year, quater);
string EndDate = CalculateEndDate(year, quater);
string SqlString = "Select * from TestTable where compl_date >= ? and compl_date <= ?";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("compl_date", StartDate); // startDate can be 1/1/2017
cmd.Parameters.AddWithValue("compl_date", EndDate); // end date could be 1/31/2017
conn.Open();
using (OleDbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
try
{
string FullLine = "";
How can I get the values that are within the above date range.
try like this;
string ConnString = getConnstring();
string DirectoryPath = getDirectortyPath(year, quater);
StreamWriter file = new StreamWriter(DirectoryPath);
string StartDate = calculateStartDate(year, quater);
string EndDate = CalculateEndDate(year, quater);
string SqlString = "Select * from TestTable where compl_date >= #StartDate and compl_date <= #EndDate";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#StartDate", StartDate);
cmd.Parameters.AddWithValue("#EndDate", EndDate);
conn.Open();
....
I would like to sum the following two columns from my database table and display it in form of a chart. My code below will run correct, but show empty chart result. Please help !
c.Open();
DateTime startDateTime = Convert.ToDateTime(textBox1.Text);
DateTime endDateTime = Convert.ToDateTime(textBox2.Text);
string query = "SELECT * FROM People_Tracking WHERE Enter_Exit_Time BETWEEN #startDateTime AND #endDateTime ;";
SqlCommand cmd = new SqlCommand(query, c);
cmd.Parameters.Add("#startDateTime", SqlDbType.DateTime).Value = startDateTime;
cmd.Parameters.Add("#endDateTime", SqlDbType.DateTime).Value = endDateTime;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable t = new DataTable();
adapter.Fill(t);
dataGridView1.DataSource = t;
string query1 = "SELECT Sum(Number_of_Enterance) FROM People_Tracking ;";
string query2 = "SELECT Sum(Number_of_Exits) FROM People_Tracking ;";
this.chart1.Series["DateTime"].Points.AddXY("Number_of_Enterance", query1);
this.chart1.Series["DateTime"].Points.AddXY("Number_of_Exits", query2);
Why the following datatable contains datetime although the expected result from my SQL query is Date ?
public static DataTable CheckCalcDateToSend(int month, int year, int camp)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ss"].ToString()))
{
StringBuilder Query = new StringBuilder();
Query.Append(" SELECT CONVERT(date, to_date) AS to_date FROM CalcAttend ");
Query.Append(" WHERE month = #month AND year = #year");
Query.Append(" AND camp = #camp AND emp_num = 0 ORDER BY calc_date");
using (SqlCommand cmd = new SqlCommand(Query.ToString(), con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#month", SqlDbType.Int).Value = month;
cmd.Parameters.AddWithValue("#year", SqlDbType.Int).Value = year;
cmd.Parameters.AddWithValue("#camp", SqlDbType.Int).Value = camp;
con.Open();
using (var dataReader = cmd.ExecuteReader())
{
dt.Load(dataReader);
}
}
}
return dt;
}
In .Net, "Date" type does not exist. Default is "DateTime" type.
"Date" property in "DateTime" variable will give date component.
Alternatively, You can try to use DataTextFormatString for dropdownlist binding.
Refer this post Date in dropdownlist
So i have a sql statement in my C# Code to try and pull data between two date ranges. Only thing is, nothing shows up.
OpenConnection(conn);
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("Select CampaignName AS 'CAMPAIGN NAME', campaignDescription AS 'CAMPAIGN DESCRIPTION', CASE WHEN EndDate >= GETDATE() and StartDate <= GETDATE() THEN 'ACTIVE' WHEN StartDate >= GETDATE() THEN 'PENDING' ELSE 'CLOSED' END as 'CURRENT STATUS', CONVERT(VARCHAR(11), StartDate,106) + ' - ' + CONVERT(VARCHAR(11),EndDate,106) AS 'CAMPAIGN DATES', Discount AS 'DISCOUNT', [Target] AS 'TARGET', Uptake AS 'UPTAKE', AddedBy AS 'ADDED BY', DateAdded AS 'DATE ADDED' FROM Tbl_Campaign WHERE startDate BETWEEN #from AND #to", conn);
try
{
SqlParameter param;
param = new SqlParameter("#from", SqlDbType.DateTime);
param.Value = txtStartDate.Text;
cmd.Parameters.Add(param);
param = new SqlParameter("#to", SqlDbType.DateTime);
param.Value = txtDateEnd.Text;
cmd.Parameters.Add(param);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
finally
{
cmd.Dispose();
conn.Close();
conn.Dispose();
}
If you scroll to the end of my Sql Command, you will see two variables for my to and from date. I tried executing this piece of code in SQL, and it works if i manually parse the dates, with '' quotation marks. I think thats what is why its not retrieving data. Could someone help me with this request?
I used a text box to get the date since your code includes "txtStartDate.Text". So, I tried your code with a simple query only to get the data in a date range. It works well. So, I think there's an issue in another place in your query.
This is the code I tried:
con = new SqlConnection();
string _connectionString = GetConnectionString();
con.ConnectionString = _connectionString;
con.Open();
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("SELECT * FROM FORDSUMD WHERE Dated BETWEEN #from AND #to",con);
try
{
SqlParameter param;
param = new SqlParameter("#from", SqlDbType.DateTime);
param.Value = txtStartDate.Text;
cmd.Parameters.Add(param);
param = new SqlParameter("#to", SqlDbType.DateTime);
param.Value = txtDateEnd.Text;
cmd.Parameters.Add(param);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
public string GetConnectionString(string databaseName = "", string serverName = "")
{
SqlConnectionStringBuilder conString = new SqlConnectionStringBuilder();
if (string.IsNullOrEmpty(serverName))
serverName = ConfigurationManager.AppSettings["ServerName"];
//Assing SQl server name
conString.DataSource = serverName;
conString.InitialCatalog = string.IsNullOrEmpty(databaseName) ? ConfigurationManager.AppSettings["DBName"] : databaseName;
conString.IntegratedSecurity = false;
conString.UserID = ConfigurationManager.AppSettings["UserId"];
conString.Password = ConfigurationManager.AppSettings["Password"];
return conString.ConnectionString;
}
If you want to use DateTimePicker control instead of the textbox control, simply replace txtStartDate.Text by dtpStart.Value(DateTimePicker) and txtDateEnd.Text by dtpEnd.Value. It will work.
How to convert a C# DateTime variable into Enum of SqlDataType.DateTime?
How to consume that enum into a connection string?
Is doing something like this correct?
string str = "SELECT * FROM TABLE WHERE CreateDt " + <that enum>;
SqlConnection Connection = new SqlConnection (<connection setting>);
Table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(str, Connection);
adapter.FillSchema(Table, SchemaType.Source);
adapter.Fill(Table);
Thank you
Your best option is to use a parameterized command:
var cmd = new SqlCommand();
cmd.Connection = conn;
DateTime MyDate = DateTime.Now;
cmd.CommandText = #"SELECT * FROM TABLE WHERE CreateDt = #MyDate";
cmd.Parameters.AddWithValue("#MyDate", #MyDate);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.FillSchema(Table, SchemaType.Source);
adapter.Fill(Table);
This is not tested, but how about:
string str = "SELECT * FROM TABLE WHERE CreateDt = #createDate";
SqlConnection Connection = new SqlConnection (<connection setting>);
Table mytable = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(str, Connection);
adapter .SelectCommand.Parameters.Add("#createDate", SqlDbType.DateTime)
adapter .SelectCommand.Parameters("#createDate").Value = <Some DateTime>
adapter.FillSchema(mytable, SchemaType.Source);
adapter.Fill(Table);