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();
....
Related
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);
}
}
I'm trying to make a query when the user clicks the End Shift button to get the total sales of the day right away without entering the date
I can't figure out how can that be possible, I'm currently using this code for it, which he has to choose 2 dates.
I tried with 1 datetimepicker but I never get a result
can it be done without the user choosing the date?
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;"))
{
conn.Open();
string query = #"select SUM(SQuantity) AS 'Total' From Sales where Sdate = #datetime";
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(query, conn);
cmd.Parameters.Add("#datetime", System.Data.OleDb.OleDbType.Date).Value = dateTimePicker1.Value;
cmd.Parameters.Add("#datetime2", System.Data.OleDb.OleDbType.Date).Value = dateTimePicker2.Value;
cmd.ExecuteNonQuery();
string result = cmd.ExecuteScalar().ToString();
textBox1.Text = #result;
}
Try this
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;"))
{
conn.Open();
string query = #"select SUM(SQuantity) From Sales where Sdate = #datetime";
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(query, conn);
cmd.Parameters.Add("#datetime", System.Data.OleDb.OleDbType.Date).Value = dateTimePicker1.Value.ToShortDateString();
//cmd.Parameters.Add("#datetime2", System.Data.OleDb.OleDbType.Date).Value = dateTimePicker2.Value;
//cmd.ExecuteNonQuery();
//string result = cmd.ExecuteScalar().ToString();
textBox1.Text = cmd.ExecuteScalar().ToString();
}
can it be done without the user choosing the date?
Yes, take a look at the #M.Rezaeyan answer.
Try
SELECT sum(SQuantity) as 'Total' FROM Sales WHERE Sdate = Date()
Final
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;"))
{
conn.Open();
string query = #"select SUM(SQuantity) AS 'Total' From Sales where Sdate = Date()";
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(query, conn);
textBox1.Text = cmd.ExecuteScalar().ToString();
}
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
I already asked a question "Timeout expired, optimize query" with problem for a time to respond sql server for my query :
using (SqlConnection sqlConn = new SqlConnection(SqlServerMasterConnection))
{
if (sqlConn.State != ConnectionState.Open) sqlConn.Open();
using (SqlCommand cmd = new SqlCommand("select DT.* from DetailTable DT, BillTable BT, PackageTable PT
where PT.Id= BT.IdPackage and DT.IdBill= BT.Id
and PT.CodeCompany = #codeCompany and PT.Date between #begin and #end",
sqlConn))
{
cmd.Parameters.Add(new SqlParameter(#begin , beginDate));
cmd.Parameters.Add(new SqlParameter("#end", endDate));
cmd.Parameters.Add(new SqlParameter("#codeCompany", codeCompany));
using (DbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//work todo
}
}
}
}
it take 28 sec for 20,000 record,
the strange behavior that I wrote this
using (SqlConnection sqlConn = new SqlConnection(SqlServerMasterConnection))
{
if (sqlConn.State != ConnectionState.Open) sqlConn.Open();
using (SqlCommand cmd = new SqlCommand("select DT.* from DetailTable DT, BillTable BT, PackageTable PT where PT.Id= BT.IdPackage and DT.IdBill= BT.Id
and PT.CodeCompany = #codeCompany and PT.Date between '" + beginDate + "' and '" + endDate + "'"
,sqlConn))
{
cmd.Parameters.Add(new SqlParameter("#codeCompany", codeCompany));
using (DbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//work todo
}
}
}
}
I changed #date with the sent value without SqlParameter and I got the result in 0 sec !!
any suggestion for this result
PS :
we save the date in the DataBase as string YYYYMMDD (PT.Date is a varchar(8))
beginDate and enddate are string like (20130904)
If your query isn't changing in structure and you're executing it with the same parameters then perhaps SQL Server is caching the results of your query, see this question for a similar issue.
I am trying to apply N before variable name for Unicode as mentioned in How to use 'LIKE' statement with unicode strings?
With the following code I am getting following error. What need to be corrected here?
Exception: Invalid column name 'N#input'.
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input ";
CODE
static void Main(string[] args)
{
string result = DisplayTest("Daily Tax Updates: ----------------- Transactions");
}
private static string DisplayTest(string searchValue)
{
string test = String.Empty;
string connectionString = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input ";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("#input", "%" + searchValue + "%");
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
test = reader.GetString(0);
}
}
}
}
}
return test;
}
I see a few issues.
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input";
should be
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE #input";
...
command.Parameters.Add("#input",System.Data.SqlDbType.NVarChar,<<size>>);
command.Parameters[0].Value = "%" + searchValue + "%";
I see you're trying to use a nvarchar parameter. I think .net does that by default with .AddWithValue
I'm not sure why do you need the typecast to nvarchar, you should be fine without the 'N' part.
That part you need when you want to specify that a string literal should be treated as nvarchar not as varchar, as in SELECT * from Table where field like N'%VALUE%'
Otherwise, you just declare your variable/parameter as nvarchar
Taken from this stack Stack overflow
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#CategoryName";
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = categoryName;
Try this one -
private static string DisplayTest(string searchValue)
{
string connectionString = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = #"SELECT AccountType,* FROM Account WHERE AccountType LIKE #input";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.CommandType = System.Data.CommandType.Text;
command.Parameters.Add("#input", SqlDbType.NVarChar);
command.Parameters["#input"].Value = string.Format("%{0}%", searchValue);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
return reader.GetString(0);
}
}
}
}
}
return String.Empty;
}