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.
Related
I am trying to select then insert a datetime from Table 1 to Table 2. I have successfully insert the data. However, the datetime shown in Table 2 is 0000-00-00 00:00:00. Idk where is the error. Someone please help me with this problem. I am struggling with this. And is this the correct way to SELECT then insert ? (Select from Table 1 then INSERT into Table 2)
try
{
string myConnectionString;
myConnectionString= "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
EncodingProvider ppp;
ppp = CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(ppp);
connection.Open();
string select = "Select time from assign where userId=#name";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.CommandText = select;
cmd.Connection = connection;
MySqlDataReader selectAssign = cmd.ExecuteReader();
selectAssign.Read();
string assign = (selectAssign["time"].ToString());
selectAssign.Close();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT into bluetooth (userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name, #stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assign);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.Connection = connection;
cmd.ExecuteNonQuery();
connection.Close();
}
catch (MySqlException ex)
{
txtExercise.Text = ex.ToString();
}
Please try with this
try
{
string myConnectionString;
myConnectionString = "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
MySqlConnection connection = new
MySqlConnection(myConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
EncodingProvider ppp;
ppp = CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(ppp);
connection.Open();
string select = "Select time from assign where userId=#name";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.CommandText = select;
cmd.Connection = connection;
MySqlDataReader selectAssign = cmd.ExecuteReader();
selectAssign.Read();
string assign = (selectAssign["time"].ToString());
selectAssign.Close();
DateTime assignDate = DateTime.Now;
DateTime.TryParseExact(assign, out assignDate);
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT into bluetooth
(userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name,
#stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assignDate);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.Connection = connection;
cmd.ExecuteNonQuery();
connection.Close();
}
catch (MySqlException ex)
{
txtExercise.Text = ex.ToString();
}
}
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
cmd.Parameters.AddWithValue("#stupid4", GetDateString(assign));
Have a method like this:
public static string GetDateString(string date)
{
DateTime theDate;
if (DateTime.TryParseExact(date, "dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out theDate))
{
// the string was successfully parsed into theDate
return theDate.ToString("dd/MM/yyyy HH:mm:ss");
}
else
{
// the parsing failed, return some sensible default value
return string.Empty;
}
}
You need to use .ExecuteReader() the use .Read() to move to each row in the result set. If you are sure the exactly one row will be returned, use .ExecuteScalar() instead. Research on the difference of both online. Below is an example using .ExecuteReader().
I also re-wrote to use using statements to simplify a bit but not deviate too much from your original code so you do not need to worry about closing and disposing resources since they inherit from IDisposable and will do that automatically once they exit the using block:
string assign = DateTime.Now.ToString();
string myConnectionString;
myConnectionString= "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
string select = "Select time from assign where userId=#name";
using (MySqlConnection con = new MySqlConnection(myConnectionString))
{
using (MySqlCommand cmd = new MySqlCommand(select))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#name", txtValue.Text);
using (MySqlDataReader cursor = cmd.ExecuteReader())
{
while (cursor.Read())
{
assign = cursor["time"];
}
}
}
string insert = "INSERT into bluetooth (userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name, #stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
using (MySqlCommand cmd = new MySqlCommand(insert))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assign);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.ExecuteNonQuery();
}
}
string s = "select idviagem from tbviagem where dia like '" + idatxt.Text + "'";
cmd = new SqlCommand(s, con);
I need the idviagem from the table tbviagem to put in idviagem from tbpassageiro (it's FK on tbpassageiro) , but i need the get idviagem from idatxt.Text it's a DateTime format, but doing the insert (look down) gives me the error:
Conversion failed when converting the nvarchar value 'select idviagem from tbviagem where dia like '06/12/2018 00:00:00'' to data type int.'
but idviagem is a int, of course .
string q = "insert into tbpassageiro (nome,cc,fotocc,idviagem) values(#n,#cc,#p,#iv)";
cmd = new SqlCommand(q, con);
con.Open();
cmd.Parameters.AddWithValue("#p", data);
cmd.Parameters.AddWithValue("#n", nometxt.Text);
cmd.Parameters.AddWithValue("#cc", cctxt.Text);
cmd.Parameters.AddWithValue("#iv", s);
cmd.ExecuteNonQuery();
You should never execute SQL statements like that but use parameters. You are using parameters for your second statement but not doing it for the first one.
Having said that, you are trying to use the query string s as the parameter value for #iv. Instead you should ExecuteScalar in first and use the result of it in second.
However, you can both get the idviagem value and do the insert in one single statement like this:
string q = #"insert into tbpassageiro
(nome,cc,fotocc,idviagem)
select #n,#cc,#p,idViagem from tbviagem where dia like #dia";
SqlCommand cmd = new SqlCommand(q, con);
cmd.Parameters.AddWithValue("#p", data);
cmd.Parameters.AddWithValue("#n", nometxt.Text);
cmd.Parameters.AddWithValue("#cc", cctxt.Text);
cmd.Parameters.Add("#dia", SqlDbType.VarChar).Value = idatxt.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Note: I don't suggest using AddWithValue, prefer Add instead.
EDIT: For sampling with a Datetime dia field:
DateTime dt;
cmd.Parameters.Add("#dia", SqlDbType.DateTime);
if (DateTime.TryParse(idatxt.Text, out dt))
{
cmd.Parameters["#dia"].Value = dt;
}
else
{
cmd.Parameters["#dia"].Value = DBNull.Value;
}
If idatxt is for getting a date\datetime value it would be much easier to use DateTimePicker to get a valid DateTime value.
It looks like you are passing the query string s as the parameter value for #iv instead of the result of that query.
I suggest executing your command cmd and passing the result value to #iv:
string s = "select idviagem from tbviagem where dia like '" + idatxt.Text + "'";
cmd = new SqlCommand(s, con);
con.Open();
Int32 resultValue = (Int32) cmd.ExecuteScalar();
string q = "insert into tbpassageiro (nome,cc,fotocc,idviagem) values(#n,#cc,#p,#iv)";
cmd = new SqlCommand(q, con);
cmd.Parameters.AddWithValue("#p", data);
cmd.Parameters.AddWithValue("#n", nometxt.Text);
cmd.Parameters.AddWithValue("#cc", cctxt.Text);
cmd.Parameters.AddWithValue("#iv", resultValue);
cmd.ExecuteNonQuery();
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.
how do I solve this error that i get when I try insert data into a table.
The error that I get is
" Conversion failed when converting date and/or time from character string"
here is my code:
Try to replace string concatenation with parameters:
Query = "INSERT INTO TblModules (Module_Code, Module_Name, Date,Start_Time, Duration) values (#ModuleCode, #Modulename, #date, #Start_Time, #Duration);";
SqlCommand cmd = new SqlCommand(Query, connection);
cmd.Parameters.AddWithValue("ModuleCode", ModuleCodeTxt.Text);
cmd.Parameters.AddWithValue("Modulename", ModulenameTxt.Text);
cmd.Parameters.AddWithValue("Date", Setdate);
cmd.Parameters.AddWithValue("Start_Time", comboBoxTime.SelectedItem);
cmd.Parameters.AddWithValue("Duration", comboBoxDuration.SelectedItem);
cmd.ExecuteNonQuery();
here is a sample code , working good
DateTime datetime = Convert.ToDateTime(Date.Text);
SqlCommand cmnd = new SqlCommand("SELECT * FROM Tech_data where Call_assign= #Call_assign and dateadd(dd, datediff(dd,0, [date_time]), 0) = #date_time ");
cmnd.Connection = con;
cmnd.Parameters.Add("#Call_assign", SqlDbType.VarChar).Value = Label1.Text;
cmnd.Parameters.Add("#date_time", SqlDbType.DateTime).Value = datetime.Date;
SqlDataAdapter da = new SqlDataAdapter(cmnd);
DataSet ds = new DataSet();
da.Fill(ds);
I want to Insert record to the database with a ComboBox. The ComboBox is connected to the other table and this is the error:
Error converting data type nvarchar to numeric.
private void InsertReceipt()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Ticket(CustomerID, Date, Store, Amount, NoStub)" +
"VALUES (#CustomerID, #Date, #Store, #Amount, #NoStub) ";
cmd.Parameters.AddWithValue("#CustomerID", cboName.SelectedValue);
cmd.Parameters.AddWithValue("#Date", dtpDate.Value.Date.ToString());
cmd.Parameters.AddWithValue("#Store", txtStore.Text);
cmd.Parameters.AddWithValue("#Amount", txtAmount.Text);
cmd.Parameters.AddWithValue("#NoStub", txtStub.Text);
cmd.ExecuteNonQuery();
}
void GetRecords2()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT CustomerID, firstname + ', ' + lastname AS Name FROM Customer";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "Customer");
cboName.DataSource = ds;
cboName.DisplayMember = "Customer.Name";
cboName.ValueMember = "Customer.CustomerID";
}
When you call AddWithValue make sure that the type of data you are passing matches the column type. Here's a likely candidate:
cmd.Parameters.AddWithValue("#Amount", txtAmount.Text);
In this line you are passing a text string to something that clearly wants a numeric value (an amount). You should parse the txtAmount.Text into a decimal first and then pass that value:
decimal amount = decimal.Parse(txtAmount.Text);
cmd.Parameters.AddWithValue("#Amount", amount);
With this code, you may still get an exception if the string in txtAmount.Text can't be parsed into a decimal, but at least then you'll know which value is causing the problem. You can/should do the same with the other values as well to make sure they match their column types.
try string.isNullorEmpty(txtAmount.text);
private void button1_Click(object sender, EventArgs e)
{
string sql;
sql = "insert into slab (date,sober_visor,tesh,shift,group,heat_no,st_grade,thick,width,length,location,pcs,remarkes,slab_no) values (#date,#sober_vsor,#tesh,#shift,#group,#heat_no,#st_grade,#thick,#width,#length,#loction,#pcs,#slab_no);select scope_identity()";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#date", txt_date.Text);
cmd.Parameters.AddWithValue("#sober_visor", com_sober_visor.ToString());
cmd.Parameters.AddWithValue("#shift", txt_shift.Text);
cmd.Parameters.AddWithValue("#heat_no", txt_heat_no.Text);
cmd.Parameters.AddWithValue("#thick", txt_shift.Text);
cmd.Parameters.AddWithValue("#width", txt_heat_no.Text);
cmd.Parameters.AddWithValue("#length", txt_length.Text);
cmd.Parameters.AddWithValue("#pcs", txt_pcs.Text);
cmd.Parameters.AddWithValue("#st_grade", txt_st_gread.Text);
cmd.Parameters.AddWithValue("#location", txt_loction.Text);
cmd.Parameters.AddWithValue("#slab_no", txt_slab_no.Text);
con.Open();
cmd.ExecuteNonQuery();
txt_heat_no.Text = cmd.ExecuteScalar().ToString();
con.Close();
MessageBox.Show("تمت عملية الإضافة");
}
}
}
cmd.Parameters.AddWithValue("#ödenecektutar", Convert.ToDecimal(tutar1.Text.Substring(0, tutar.Text.Length - 1)));