How to insert date time in database? - c#

I'am making a time attendance system and I don't know how to store datetime in database. I really need some help with my system if anyone has any code for time attendance please share your Code a little help would do thanks..
Here is my Code:
con = newSqlConnection(#"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
dt = new DataTable();
cmd = new SqlCommand(#"SELECT EmpID FROM data WHERE EmpID='" + Code.Text + "'", con);
con.Open();
sdr = cmd.ExecuteReader();
int count = 0;
while (sdr.Read())
{
count = count + 1;
}
con.Close();
if (count == 1)
{
con.Open();
DateTime dtn = DateTime.Now;
dtn = Convert.ToDateTime(DateTime.Now.ToString("hh:mm"));
string query = #"INSERT INTO Time (TimeIn) Values ('" + dtn + "')";
cmdd = new SqlCommand(query, con);
sdr = cmdd.ExecuteReader();
sdr.Read();
dataGridView.DataSource = databaseDataSet.Time ;
con.Close();
MessageBox.Show("Verify Ok");
}
else
{
MessageBox.Show("Please Try Again");
}

Do not use ExecuteReader() but ExecuteNonQuery(); add query parameters, do not modify query text, technically it could be something like that:
...
if (count == 1) {
...
DateTime dtn = DateTime.Now;
string query =
#"insert into Time (
TimeIn)
values (
#TimeIn)"; // <- query parameter instead of query text modification
using (var query = new SqlCommand(query, con)) {
// bind query parameter with its actual value
query.Parameters.AddWithValue("#TimeIn", dtn);
// Just execute query, no reader
query.ExecuteNonQuery();
}
...
However, table Time as it appears in the question looks very strange, hardly does it contain TimeIn field only.

Related

Updating values from excel to database

I am facing difficulty on writing logic to insert data into the database from some array. My requirement is if the data already exist in SQL insert query should not be executed. only when that data does not exist in database the insert query has to be executed where data will be inserted. I have tried a lot please find my code below.
public void writetodatabase()
{
//SQL connection String
SqlConnection cnn = new SqlConnection(#"Data Source=ABDUL-TPS\TPSSQLSERVER;Initial Catalog=Automation;Integrated Security=True");
// Open Connection to sql
cnn.Open();
// Declare a DataTable which will contain the result from SQL query
DataTable DT = new DataTable();
for(int m =0; m < globalZoho_Names.Length; m++)
{
string query1 = "select * from tbl_Zoho_data where col_Zoho_SKU like '" + globalZoho_SKU[m] + "'";
SqlCommand cmd1 = new SqlCommand(query1, cnn);
SqlDataReader reader1 = cmd1.ExecuteReader();
while (reader1.Read())
{
string zohosku = reader1["col_Zoho_SKU"].ToString();
if (zohosku == null)
{
string ItemName = reader1["col_item_name"].ToString();
string insert1 = "insert into tbl_zOHO_DATA values ('" + globalZoho_SKU[m] + "','" + globalZoho_Names[m] + "')";
SqlDataAdapter DA_insert = new SqlDataAdapter(insert1, cnn);
DA_insert.Fill(DT);
Label1.Text = "Khulja Sim Sim";
}
}
reader1.Close();
}
}
I want the code to check for the values first into the database and then insert only those values which do not exist in the database.

Check SQL for Book_Availability before issuing one (BookAvailability-1)

If I put "if, foreach, and else statement under comment //", the program works and Reduces book count by 1 from SQL database. But I want to check IF there is at least 1 available book to give. This code keeps showing me the message in "else" statement if I leave it like this. Help is needed fast, it's my final project, that is needed to be done before 23.07. :(
int book_qty = 0;
SqlCommand cmd2 = connection.CreateCommand();
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "SELECT * FROM Book_list WHERE BookName = '" + TextBoxBookName + "'";
cmd2.ExecuteNonQuery();
DataTable dt2 = new DataTable();
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
da2.Fill(dt2);
foreach (DataRow dr2 in dt2.Rows)
{
book_qty = Convert.ToInt32(dr2["book_qty"].ToString());
}
if (book_qty > 0)
{
SqlCommand cmd = connection.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Issue_book VALUES(" + TextBoxSearchMembers.Text + ",'" + TextBoxMemberName.Text + "','" + TextBoxMemberContact.Text + "','" + TextBoxMemberEmail.Text + "','" + TextBoxBookName.Text + "', '" + DateTimePicker1.Text + "')";
cmd.ExecuteNonQuery();
SqlCommand cmd1 = connection.CreateCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "UPDATE Book_list SET BookAvailability = BookAvailability-1 WHERE BookName ='" + TextBoxBookName.Text + "'";
cmd1.ExecuteNonQuery();
MessageBox.Show("successful issue");
this.Close();
else
{
MessageBox.Show("Book not available");
}
You are only checking book_qty from the last row in your result set instead of BookAvailability for all rows. You probably want to do something like:
SqlCommand cmd2 = connection.CreateCommand();
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "SELECT BookAvailability FROM Book_list WHERE BookName = '" + TextBoxBookName + "'";
var result = cmd2.ExecuteScalar();
book_qty = Convert.ToInt32(result);
You need to make sure that there is only one book with the given bookname available.
In that case just correcting this one line in your code would help as well:
book_qty = Convert.ToInt32(dr2["book_qty"].ToString());
to
book_qty = Convert.ToInt32(dr2["BookAvailability"].ToString());
Otherwise you'd need to query SUM(BookAvailability), but the following code would decrease the amount of books for multiple books at once, that wouldn't be good.
Untested code. I don't have your database. Comments and explanation in line.
private void OPCode()
{
try
{
//keep your connections close to the vest (local)
using (SqlConnection connection = new SqlConnection())
//a using block ensures that your objects are closed and disposed
//even if there is an error
{
using (SqlCommand cmd2 = new SqlCommand("SELECT BookAvailability FROM Book_list WHERE BookName = #BookName", connection))
{
//Always use parameters to protect from sql injection
//Also it is easier than fooling with the single quotes etc.
//If you are referring to a TextBox you need to provide what property is
//being accessed. I am not in a WPF right now and not sure if .Text
//is correct; may be .Content
//You need to check your database for correct data type and field size
cmd2.Parameters.Add("#BookName", SqlDbType.VarChar, 100).Value = TextBoxBookName.Text;
//A select statement is not a non-query
//You don't appear to be using the data table or data adapter
//so dump them extra objects just slow things dowm
connection.Open();
//Comment out the next 2 lines and replaced with
//Edit Update
//var returnVal = cmd2.ExecuteScalar() ?? 0;
//if ((int)returnVal > 0)
//*************************************************************
//Edit Update
//*************************************************************
//in case the query returns a null, normally an integer cannot
//hold the value of null so we use nullable types
// the (int?) casts the result of the query to Nullable of int
Nullable<int> returnVal = (int?)cmd2.ExecuteScalar();
//now we can use the .GetValueOrDefault to return the value
//if it is not null of the default value of the int (Which is 0)
int bookCount = returnVal.GetValueOrDefault();
//at this point bookCount should be a real int - no cast necessary
if (bookCount > 0)
//**************************************************************
//End Edit Update
//**************************************************************
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO issue_book VALUES(#SearchMembers etc", connection))
{
//set up the parameters for this command just like the sample above
cmd.Parameters.Add("#SearchMembers", SqlDbType.VarChar, 100).Value = TextBoxSearchMembers.Text;
cmd.ExecuteNonQuery();
}
using (SqlCommand cmd1 = new SqlCommand("UPDATE Book_list SET BookAvailability = BookAvailability-1 WHERE BookName = #BoxBookName;", connection))
{
cmd1.Parameters.Add("#BoxBookName", SqlDbType.VarChar, 100);
cmd1.ExecuteNonQuery();
}
MessageBox.Show("success");
this.Close();
}
else
{
MessageBox.Show("Book not available");
}
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
}
}

Check row count and then insert value

I have a form and i have a listbox in it to select multiple values of different dates. but requirement is one date can be booked for 2 users only once 2 users book the date then i just have to remove it from listbox.
I have created 3 tables. One table (table_dates) is just shows the dates in different rows and second table (table_users) is storing users information and third table (table_map) is mapping user with the dates.
How to write a logic to check if selected date is registered by 2 users already?
Please check my c# code below
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO table_users(Name,Email) OUTPUT INSERTED.userId Values (#name,#email)";
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#email", email);
int lastId = (int)cmd.ExecuteScalar();
if (lastVolId > 0)
{
SqlCommand cmd2 = new SqlCommand();
int counter = 0;
string query = "";
foreach (ListItem li in listBox.Items)
{
if (li.Selected)
{
// I need to write some thing here to check if selected date is registered 2 times
query = "INSERT INTO table_map(userId,dateId) VALUES('" + lastId + "','" + li.Value + "')";
cmd2 = new SqlCommand(query, conn);
cmd2.ExecuteNonQuery();
counter++;
}
}
}
else
{
//Error notification
}
}
Does you table_Date has a column for a unique dateID? It is mendatory for operation u want to perform.
What u need to do is Perform a SELECT QUERY to check if it exists twice.
String selectStatent="SELECT * FROM table_Map WHERE dateID = #dateID";
SqlCommand selectCommand = new SqlCommand( selectStatement, connectionString);
int rowCount = selectCommand.ExecuteScalaer();
if( rowCount <= 2)
{
//Proceed
}

sql server strange behavior (query time respond)

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.

DateTime format wrong C# , Oracle

In my app I capture a "Timestamp". This timestamp I later use when I call a stored procedure. At the moment I'm getting the error :
ORA-01830: date format picture ends before converting entire input
string ORA-06512: at line 2
I need hour,min and sec because the column in the table must be unique.
Here is how i get my datetime:
private void getDate()
{
conn.Open();
string query;
query = "select to_char(sysdate, 'dd/mon/yyyy hh24:mi:ss') as CurrentTime from dual";
OracleCommand cmd = new OracleCommand(query, conn);
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
text = dr[0].ToString();
dr.Close();
conn.Close();
}
This is how I call the procedure:
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
conn.Open();
OracleTransaction trans = conn.BeginTransaction();
cmd.CommandTimeout = 0;
cmd.CommandText = "dc.hhrcv_insert_intrnl_audit_scn";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("pn_pallet_id", OracleDbType.Number).Value = palletid;
cmd.Parameters.Add("pn_emp_id_no", OracleDbType.Number).Value = empid;
cmd.Parameters.Add("pd_intrnl_audit_scan_datetime", OracleDbType.VarChar).Value = text;
cmd.Parameters.Add("pn_company_id_no", OracleDbType.VarChar).Value = companyIdNo2;
cmd.Parameters.Add("pn_order_no", OracleDbType.Number).Value = orderNo2;
cmd.Parameters.Add("pn_carton_code", OracleDbType.Number).Value = carton_Code2;
cmd.Parameters.Add("pn_no_of_full_carton", OracleDbType.Number).Value = txtNoOfCartons.Text;
cmd.Parameters.Add("pn_no_of_packs", OracleDbType.Number).Value = txtNoOfPacks.Text;
cmd.Parameters.Add(new OracleParameter("pv_error", OracleDbType.VarChar));
cmd.Parameters["pv_error"].Direction = ParameterDirection.Output;
string pv_error;
cmd.ExecuteNonQuery();
pv_error = cmd.Parameters["pv_error"].Value.ToString();
if (pv_error.ToString() == "")
{
trans.Commit();
frmMsgAudit ms = new frmMsgAudit(empid,palletid,orderno,text);
ms.Show();
this.Hide();
}
else
{
trans.Rollback();
MessageBox.Show("" + pv_error, "Error");
}
conn.Close();
Getting the error on:
cmd.ExecuteNonQuery();
ORA-01830: date format picture ends before converting entire input
string ORA-06512: at line 2
Thanks in advance.
Thanks for all the quick responses!
grrr.. I really need to sit and walk through everything step by step! Anyways, this was the issue:
In stored procedure i had:
...
begin
insert into dc_internal_audit_scan (pallet_id_no,
internal_audit_scan_emp,
internal_audit_scan_datetime,
company_id_no,
order_no,
carton_code,
no_of_full_cartons,
no_of_packs,
last_update_datetime,
username)
values (ln_pallet_id_no,
pn_emp_id_no,
**pd_intrnl_audit_scan_datetime,**
pn_company_id_no,
pn_order_no,
pv_carton_code,
pn_no_of_full_cartons,
pn_no_of_packs,
sysdate,
lv_emp_username);
end;
now:
...
begin
insert into dc_internal_audit_scan (pallet_id_no,
internal_audit_scan_emp,
internal_audit_scan_datetime,
company_id_no,
order_no,
carton_code,
no_of_full_cartons,
no_of_packs,
last_update_datetime,
username)
values (ln_pallet_id_no,
pn_emp_id_no,
**TO_DATE(pd_intrnl_audit_scan_datetime,'dd/mon/yyyy hh24:mi:ss'),**
pn_company_id_no,
pn_order_no,
pv_carton_code,
pn_no_of_full_cartons,
pn_no_of_packs,
sysdate,
lv_emp_username);
end;
TO_DATE(pd_intrnl_audit_scan_datetime,'dd/mon/yyyy hh24:mi:ss')
thanks
Looks like this line is wrong;
query = "select to_char(sysdate, 'dd/mon/yyyy hh24:mi:ss')
What 24 doing here?
Try with;
query = "select to_char(sysdate, 'dd/mon/yyyy hh:mi:ss AM')
FROM ORA-01830 Error
You tried to enter a date value, but the date entered did not match
the date format.
EDIT: Since A.B.Cade warned me, hh24 is a valid oracle format, but still I believe your sysdate's format and 'dd/mon/yyyy hh24:mi:ss' are different formats.

Categories