Select with oledb - c#

I Can't do select...
I can not do a select inside a go with dates
recebe uma variavel que determina quantidade de meses a ser calculada MesesDemanda
Calculated a date before and one after
for (int i = 1; i <= MesesDemanda; i++)
{
int cont = 0;
DateTime dataposterior = DateTime.Now, dataanterior = DateTime.Now;
dataanterior = dataanterior.AddMonths(i);
dataposterior = dataposterior.AddMonths(-(i - 1));
con.Open();
cmd = new OleDbCommand("SELECT HistSaida.dataHistSaida, HistSaida.idProdutoHistSaida, HistSaida.qtdHistSaida FROM HistSaida WHERE (((HistSaida.dataHistSaida) BETWEEN #" + dataanterior + "# AND #" + dataposterior + "#) AND idProdutoHistSaida = " + idProduto + ")", con);
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Demanda = Demanda + Convert.ToInt32(dr["qtdHistSaida"]);
cont = 1;
}
}
dr.Close();
con.Close();
Valordivisao = Valordivisao + cont;
}

Use parameters like below
cmd = new OleDbCommand("SELECT dataHistSaida, idProdutoHistSaida, qtdHistSaida FROM HistSaida WHERE ((dataHistSaida <=? AND dataHistSaida >= ?) AND idProdutoHistSaida = ?)", con);
now you can set values like below
cmd.Parameters.AddWithValue("#p1", dataanterior );
cmd.Parameters.AddWithValue("#p2", dataposterior );
cmd.Parameters.AddWithValue("#p3", idProduto );
if you need to take Sum of qtdHistSaida column then you can change the sql statement as below
SELECT SUM(qtdHistSaida) FROM HistSaida WHERE ((dataHistSaida <=? AND dataHistSaida >= ?) AND idProdutoHistSaida = ?)
now you can use ExecuteScalar method to get the sum value as below
var result = cmd.ExecuteScalar();

Related

Code execution is not going down

I have a code below and it has strange behavior,Line of code after closing of While Loop is not executing. If i write those lines before While loop they got executed. I have searched a lot on this issue but failed.
if ((Convert.ToInt32(newDt.Rows[i]["qty"])) > (Convert.ToInt32(newDt1.Rows[i]["qty"])))
{
k_batch = Convert.ToInt32(newDt.Rows[i]["batch_num"]);
label20.Content = k_batch.ToString();
var dqty = (from row in Addition_result.AsEnumerable() //retriving value from DataTable
where row.Field<int>("batch_num") == k_batch
select row.Field<int>("qty")).FirstOrDefault();
dqty_y = Convert.ToInt32(dqty);
label16.Content = dqty_y.ToString();
con.Open();
SqlCommand cmd1 = new SqlCommand("SELECT quantity,sold_qty,left_qty FROM batch WHERE id='" + k_batch + "'", con);
SqlDataReader batch_qty_details = null;
batch_qty_details = cmd1.ExecuteReader();
while (batch_qty_details.Read())
{
label16.Content = dqty_y.ToString();
batch_qty = Convert.ToInt32(batch_qty_details["quantity"]);
batch_left = Convert.ToInt32(batch_qty_details["left_qty"]);
batch_sold = Convert.ToInt32(batch_qty_details["sold_qty"]);
} //code after this is not executing
label18.Content = batch_left.ToString();
label19.Content = batch_sold.ToString();
label21.Content = dqty_y.ToString();
label22.Content = batch_qty.ToString();
label16.Content = batch_sold + dqty_y;
label17.Content = batch_left - dqty_y;
if (((batch_sold + dqty_y) <= batch_qty) && ((batch_left - dqty_y) >= 0))
{
SqlCommand command = new SqlCommand("update batch set sold_qty=sold_qty+#soldqty2, left_qty=left_qty-#soldqty2 where id=#id2", con);
command.Parameters.AddWithValue("#soldqty2", Convert.ToInt32(dqty_y));
command.Parameters.AddWithValue("#id2", Convert.ToInt32(k_batch));
rexe = command.ExecuteNonQuery();
}
else
{
MessageBox.Show("Please Check you Ordered Quantity !");
}
con.Close();
}
}
Actually there was issue that connection state was already Open and i was trying to open it again. So then i used try-catch block it told me that connection is already open. Now i have changed my code and here it is.
if ((Convert.ToInt32(newDt.Rows[i]["qty"])) > (Convert.ToInt32(newDt1.Rows[i]["qty"])))
{
k_batch = Convert.ToInt32(newDt.Rows[i]["batch_num"]);
label20.Content = k_batch.ToString();
var dqty = (from row in Addition_result.AsEnumerable() //retriving value from DataTable
where row.Field<int>("batch_num") == k_batch
select row.Field<int>("qty")).FirstOrDefault();
dqty_y = Convert.ToInt32(dqty);
label16.Content = dqty_y.ToString();
try
{
//con.Open();
SqlCommand cmd1 = new SqlCommand("SELECT quantity,sold_qty,left_qty FROM batch WHERE id='" + k_batch + "'", con);
SqlDataReader batch_qty_details = null;
batch_qty_details = cmd1.ExecuteReader();
while (batch_qty_details.Read())
{
label16.Content = dqty_y.ToString();
batch_qty = Convert.ToInt32(batch_qty_details["quantity"]);
batch_left = Convert.ToInt32(batch_qty_details["left_qty"]);
batch_sold = Convert.ToInt32(batch_qty_details["sold_qty"]);
}
con.Close();
}
catch(Exception EX)
{
MessageBox.Show(EX.ToString());
}
label18.Content = batch_left.ToString();
label19.Content = batch_sold.ToString();
label21.Content = dqty_y.ToString();
label22.Content = batch_qty.ToString();
label16.Content = batch_sold + dqty_y;
label17.Content = batch_left - dqty_y;
if (((batch_sold + dqty_y) <= batch_qty) && ((batch_left - dqty_y) >= 0))
{
con.Open();
SqlCommand command = new SqlCommand("update batch set sold_qty=sold_qty+#soldqty2, left_qty=left_qty-#soldqty2 where id=#id2", con);
command.Parameters.AddWithValue("#soldqty2", Convert.ToInt32(dqty_y));
command.Parameters.AddWithValue("#id2", Convert.ToInt32(k_batch));
rexe = command.ExecuteNonQuery();
}
else
{
check_qty = -1;
}
}

Continuation about Getting date between two dates

My datagridview displays date with the year 2015, even if I set my two datetimepickers from two different dates but with the same year (2016).
Heres my code..
public static List<Retailer> GetDataAllRetailer(DateTime past, DateTime present)
{
List<Retailer> data = new List<Retailer>();
MySqlConnection con = DBConnection.ConnectDatabase();
try
{ // AND
MySqlCommand cmd = new MySqlCommand("SELECT * FROM " + tablename + " WHERE (date BETWEEN '" + past.ToString("MM-dd-yyyy") + "' AND '" + present.ToString("MM-dd-yyyy") + "') ", con);
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Retailer rawData = new Retailer();
rawData.Date = reader.GetString(1);
rawData.Walletid = reader.GetString(0);
rawData.Fname = reader.GetString(2);
rawData.Lname = reader.GetString(3);
rawData.Birthdate = reader.GetString(4);
rawData.Address = reader.GetString(5);
rawData.Province = reader.GetString(6);
rawData.City = reader.GetString(7);
rawData.Balance = reader.GetDouble(8);
rawData.Frozen = reader.GetDouble(9);
rawData.Sponsor_id = reader.GetString(10);
rawData.Share = reader.GetDecimal(11);
rawData.Email = reader.GetString(12);
rawData.Password = reader.GetString(13);
rawData.Type = reader.GetInt32(14);
data.Add(rawData);
}
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
return data;
}
}
If the table column is varchar, then I suggest you to convert it to date to do the search appropriately as follows:
SELECT * FROM Table WHERE
CONVERT(DATE, FromDate) >= CONVERT(DATE, '2016-09-03')
AND CONVERT(DATE, ToDate) <= CONVERT(DATE, '2016-09-13')

SQL update command in c#

I have a SQL Server table with columns like this:
Mobile No <> OTP <> GenTime <> AuthTime <> IsAuth
9632587410 <> 256389 <> ****** <> ******** <> False
9876543210 <> 258963 <> ***** <> ****** <> False
so on ...
using (SqlConnection conn = new SqlConnection())
{
string inputn = Console.ReadLine();
long mobileNo;
long.TryParse(inputn, out mobileNo);
string inputo = Console.ReadLine();
int OTP;
Int32.TryParse(inputo, out OTP);
DateTime now = DateTime.Now;
conn.ConnectionString = "Data Source=10.0.0.98;Initial Catalog=TeletextCMS_Dev;User ID=Testteam;Password=Cognigent33#";
conn.Open();
//long r = 8947052876;
SqlCommand command = new SqlCommand("SELECT * FROM CustomerAuthOTP WHERE MobileNum=" + mobileNo, conn);
int f = 0;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
//int OTP = reader[1];
int OTPGen = int.Parse(string.Format("{0}", reader[1]));
int a = now.Hour;
int b = now.Minute;
int e = now.Day;
DateTime then = DateTime.Parse(string.Format("{0}", reader[2]));
int c = then.Hour;
int d = then.Minute;
int g = then.Day;
if (e == g)
{
int t = (a - c) * 60 + b - d;
if (OTP == OTPGen && e == g && t <= 15)
{
Console.WriteLine("Hi");
f = 1;
}
else
{
Console.WriteLine("No");
}
}
if (e > g)
{
int t = (a + 24 - c) * 60 + b - d;
if (OTP == OTPGen && e == g && t <= 15)
{
Console.WriteLine("Hi");
f = 1;
}
else
{
Console.WriteLine("No");
}
}
}
}
if(f == 1)
{
SqlCommand cmd = new SqlCommand("UPDATE CustomerAuthOTP SET IsAuthenticated=True, AuthenticationTime=" + now, conn);
Console.WriteLine("Hi");
}
}
Now at the bottom I have an Update command. I tried to execute it but it is not doing anything.
There is no error in the code. Kindly some one help me out if f== 1 then in the CustomerAuthOTP table update the IsAuthenticated value to be true and also set the authentication time to now.DateTime()
First of all you should execute your commnd:
SqlCommand cmd = new SqlCommand("UPDATE CustomerAuthOTP SET IsAuthenticated=True, AuthenticationTime=" + now, conn);
cmd.ExecuteNonQuery();
I recommend to use SqlCommand.Parameters
var commandText = "UPDATE CustomerAuthOTP SET IsAuthenticated=#IsAuthenticated, AuthenticationTime=#AuthenticationTime";
SqlCommand cmd = new SqlCommand(commandText, conn);
cmd.Parameters.AddWithValue("#IsAuthenticated", true);
cmd.Parameters.AddWithValue("#AuthenticationTime", now);
cmd.ExecuteNonQuery();
It'll help SQL provider to determine parameter types and protects against SQL-injections.
DateTime now = DateTime.Now;
...
SqlCommand cmd = new SqlCommand(
"UPDATE CustomerAuthOTP SET IsAuthenticated=True, AuthenticationTime="
+ now, conn);
Note that this will be a string concatenation, and (depending on your locale, etc), the following is not valid TSQL:
UPDATE CustomerAuthOTP SET IsAuthenticated=True, AuthenticationTime=08/12/2015 12:08:32
The immediate problem is formatting (both the datetime and the boolean are wrong), but it is best fixed by parameterization - you should almost never be concatenating values into TSQL:
SqlCommand cmd = new SqlCommand(
"UPDATE CustomerAuthOTP SET IsAuthenticated=1, AuthenticationTime=#now", conn);
cmd.Parameters.AddWithValue("now", now);
cmd.ExecuteNonQuery();
Or with a tool like "dapper":
conn.Execute("UPDATE CustomerAuthOTP SET IsAuthenticated=1, AuthenticationTime=#now",
new { now });

Reset Autonumber in C# based on year and date using oracle database

i have auto generate number create automatically in C#. this sample like this PPP-150500001 , PPP-150500002 => PPP- is a string never change, 15 is a year, 05 is a date, and 00001 is auto generate number.
How Can i reset auto number after get a new year like PPP-160100001 .
this is my method:
public void NomerUrut()
{
long hitung;
string urut;
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = #"SELECT NOPERMOHONAN FROM PERMOHONAN WHERE NOPERMOHONAN IN (SELECT MAX(NOPERMOHONAN)
FROM PERMOHONAN) ORDER BY NOPERMOHONAN DESC";
cmd.Connection = koneksi_manual.con;
koneksi_manual.con.Open(); //open connection
dr = cmd.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
hitung = Convert.ToInt64(dr[0].ToString().Substring(dr["NOPERMOHONAN"].ToString().Length - 5, 5)) + 1;
string joinstr = "00000" + hitung;
DateTime dt = DateTime.Now; // take years and date in autonumber
urut = "PPP-" + dt.ToString("yy") + dt.ToString("MM") + joinstr.Substring(joinstr.Length - 5, 5);
//it will show PPP-150500002, PPP-150500003, etc
//how can i reset this autonumber after get new years like PPP-160100001
}
else
{
urut = "PPP-150500001"; // first form load will display this default autonumber
}
dr.Close();
txtNoPermohonan.Text = urut; //display auto generate number in a textbox
koneksi_manual.con.Close(); //close connection
}
Solved.
i have update for this question and i can finish it using another query to solve my problem. i can reset it every years..
this my update code:
public static string GenerateKodeUrut()
{
string nomor = "";
string date = DateTime.Now.ToString("yyyy/MM/dd").Substring(2, 2);
DateTime dt = DateTime.Now;
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = (#"SELECT NOPERMOHONAN from PERMOHONAN
where substr(NOPERMOHONAN, 5,2) ='" + date + "' ORDER BY cast(substr(NOPERMOHONAN, 9,5) as number) DESC");
cmd.Connection = koneksi_manual.con;
dr = cmd.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
string nmrTerakhir = (dr["NOPERMOHONAN"]).ToString().Remove(0, 8);
nomor = "PPP-" + date + dt.ToString("MM") + (Convert.ToInt32(nmrTerakhir) + 1).ToString("0000#");
}
else
{
nomor = "PPP-" + date + dt.ToString("MM") + "00001";
}
return nomor;
}
you can make a flage in your db to check it && your date.
i hope that code give you my idea
bool flage = false;
int checkdate = Convert.ToInt16(dt.ToString("MM"));
if (checkdate == 12) {
flage = true;
}
if (flage == true && checkdate == 1) {
//Write Your Code Here
flage = false;
}

SqlDataReader in C#

I have a problem with SqlDataReader.
Here's my code. the problem is when I debug it it doesn't go further than
while(dr.read())
it means the value returned by dr.Read() is false. I don't know what's wrong.
if (CS_time_date[i].Substring(0, 2) == "CS")
{
string cardserial = CS_time_date[i].Substring(4, 5);
try
{
using (SqlConnection con = new SqlConnection(WindowsAppEmp.Properties.Settings.Default.Database1ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from Card_reg ", con);
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
if ((dr["Cardserial"].ToString() == cardserial))
{
flag = 1;
string EmpID = dr["Id"].ToString();
string F_Name = dr["fname"].ToString();
string L_Name = dr["lname"].ToString();
// Insert_EmpReport(EmpID, F_Name, L_Name, cardserial, CS_time_date,con);
string strsql1 = "Insert into Emp_Report (EmpId,CS,fname,lname,CheckIn,CheckOut,Date,Status) values (#EmpID,#Cs,#fname,#lname,#CheckIn,#CheckOut,#Date,#Status)";
SqlCommand report_cmd = new SqlCommand(strsql1, con);
report_cmd.Parameters.AddWithValue("#EmpID", EmpID);
report_cmd.Parameters.AddWithValue("#Cs", cardserial);
report_cmd.Parameters.AddWithValue("#fname", F_Name);
report_cmd.Parameters.AddWithValue("#lname", L_Name);
if (CS_time_date[i].Substring(9, 10) == "56")
if (CS_time_date[i + 2] == DateTime.Now.ToString("dd/mm/yyyy"))
{
report_cmd.Parameters.AddWithValue("#CheckIn", CS_time_date[i + 1]);
report_cmd.Parameters.AddWithValue("#Status", "Present");
}
else
report_cmd.Parameters.AddWithValue("#Status", "Absent");
else
report_cmd.Parameters.AddWithValue("#CheckOut", CS_time_date[i + 1]);
report_cmd.Parameters.AddWithValue("#Date", CS_time_date[i + 2]);
}
else
flag = 0;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
} while (reader.Peek() != -1);
reader.Close();
It looks like you have the Card_reg table defined in your database but this table doesn't contain any values in it - it is empty. That's why the select * from Card_reg query doesn't return any results and the data reader has nothing to read.

Categories

Resources