I need to insert a row in my table in oracle from C# (Windows Forms)
conn.Open();
OracleCommand cmd = new OracleCommand("INSERT INTO RECIPES(id,name,time_cooking,time_prep,price,directions,user_name,submit_timestamp) VALUES (:id, :name, :time_cook, :time_prep, :price, :directions, :user_name, :sub_time)",conn);
cmd.Parameters.AddWithValue(":id",x);
cmd.Parameters.AddWithValue(":name",textBox10.Text);
cmd.Parameters.AddWithValue(":time_cook", textBox9.Text);
cmd.Parameters.AddWithValue(":time_prep",textBox8.Text);
cmd.Parameters.AddWithValue(":price", textBox6.Text);
cmd.Parameters.AddWithValue(":directions",richTextBox2.Text);
cmd.Parameters.AddWithValue(":user_name",this.username);
cmd.Parameters.AddWithValue(":sub_time",DateTime.Now.ToString("MM/dd/yyyy"));
try
{
cmd.ExecuteNonQuery();
}
catch (OracleException ex)
{
MessageBox.Show(ex.ToString());
}
conn.Close();
I get the error below.
ORA-01843: not a valid month
I checked in oracle :
select *
from nls_session_parameters;
and returned NLS_DATE_FORMAT mm/dd/yyyy
You shouldn't pass the date as a string; you should pass it as a date instead... just remove the ToString call:
cmd.Parameters.AddWithValue(":sub_time", DateTime.Now);
If you pass a string, it will be parsed using the format specified by the nls_date_format parameter in the database. If the format you pass is not the one the database expects, the parsing will fail. By passing the date itself, you don't need to worry about the format.
Related
private void button2_Click(object sender, EventArgs e)
{
try
{
using (var con = new OleDbConnection())
{
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ZwaneZP01\source\repos\HenleyFaultsSystemSbu\Faults.accdb;";
con.Open();
using (var com = new OleDbCommand())
{
com.Connection = con;
com.CommandText = "INSERT INTO Faults ([Date],[Job],[Area],[ReportedBy],[ReportedTo],[Equipment],[Workshop]," +
"[SerialNo],[Delay],[TimeSpent],[FANo],[Category],[Fault],[Action],[Status]) " +
"VALUES (#Date,#Job,#Area,#ReportedBy,#ReportedTo,#Workshop,#Equipment,#Fault,#Action,#Delay,#TimeSpent,#Status,#SerialNo,#FANo,#Category)";
com.Parameters.AddWithValue("#Date", dateTimePicker1.Text);
com.Parameters.AddWithValue("#Job", comboBox1.Text);
com.Parameters.AddWithValue("#Area", AreacomboBox2.Text);
com.Parameters.AddWithValue("#ReportedBy", NameCodeReportedBy.Text);
com.Parameters.AddWithValue("#ReportedTo", ReportedToBox.Text);
com.Parameters.AddWithValue("#Workshop", WorkshopBox.Text);
com.Parameters.AddWithValue("#Equipment", EquipmentBox.Text);
com.Parameters.AddWithValue("#Fault", textBox2.Text);
com.Parameters.AddWithValue("#Action", textBox3.Text);
com.Parameters.AddWithValue("#Delay", DelayBox.Text);
com.Parameters.AddWithValue("#TimeSpent", TimeBox.Text);
com.Parameters.AddWithValue("#Status", checkBox1.Checked);
com.Parameters.AddWithValue("#SerialNo", textBox4.Text);
com.Parameters.AddWithValue("#FANo", textBox5.Text);
com.Parameters.AddWithValue("#Category", CategoryComboBox.Text);
com.ExecuteNonQuery();
}
}
MessageBox.Show("Saved");
}
catch (Exception ex)
{
MessageBox.Show("Not saved: " + ex.Message);
}
}
//So this is not saving to the database
I tried changing the date format as I thought its probably the date but that has not helped either
I expect it to save to the data but I am getting an error about criteria mismatch
The first thing to fix is removing all those AddWithValue and replacing them with
com.Parameters.Add("#Date", OleDbType.DateTime).Value = dateTimePicker1.DateTime;
and so on...
This is important because AddWithValue is not able to pass a parameter of type DateTime as expected by your database table if you give it a string of text. You should alwasy be
precise when providing parameters to your underlying database (MS-Access or not)
But then there is another problem. The OleDb library is not able to recognize the parameters by their names and assign the value to the correct place in your sql.
OleDb pass the parameters values looking at their position in the collection so the parameter #Workshop is assigned to the Equipment field and viceversa the parameter #Equipment is assigned to the Workshop field.
You should arrange your parameter list following the exact order in which the parameter placeholders appears in the sql text and, of course, verify that every parameter placeholder matches the corresponding field to update
I am trying to insert date in my database table through a textbox. But even if I am converting the string into Datetime I am still getting this error :
"The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value".
I have taken datetime datatype in my database. This is my code :
try
{
SqlCommand cmd = new SqlCommand(#"INSERT INTO tblProject(project_starting_date,project_ending_date)values(#projectstartingdate,#projectendendingdate)", objconn);
//cmd.Parameters.AddWithValue("#projectstartingdate", DateTime.Parse(txtStartingdate.Text).ToString());
//cmd.Parameters.AddWithValue("#projectendendingdate", DateTime.Parse(txtProjectendingdate.Text).ToString());
DateTime stdate;
if(DateTime.TryParse(txtStartingdate.Text, out stdate))
{
//cmd.Parameters.AddWithValue("#projectstartingdate",stdate);
SqlParameter projstrtdate = new SqlParameter("#projectstartingdate", SqlDbType.DateTime);
projstrtdate.Value = stdate;
cmd.Parameters.Add(projstrtdate);
}
DateTime enddate;
if (DateTime.TryParse(txtProjectendingdate.Text, out enddate))
{
//cmd.Parameters.AddWithValue("#projectendendingdate", enddate);
SqlParameter projenddate = new SqlParameter("#projectendendingdate", SqlDbType.DateTime);
projenddate.Value = enddate;
cmd.Parameters.Add(projenddate);
}
if (objconn.State == ConnectionState.Closed)
{
objconn.Open();
}
norowaffected = cmd.ExecuteNonQuery();
objconn.Close();
}
catch (Exception ex)
{
Response.Write( ex.ToString());
}
Please guide me where I am doing wrong?
Probably your locale configuration is trying to convert the data string in a wrong unexpected format.
Try with the following:
if(DateTime.TryParse(txtStartingdate.Text, out stdate)
{
SqlParameter projectStartingDateParam = new SqlParameter("#projectstartingdate", SqlDbType.DateTime);
projectStartingDateParam.Value = stdate;
cmd.Parameters.Add(projectStartingDateParam);
}
Do the same with "projectendingdate". Create a SqlParameter with SqlDbType equals to SqlDbType.DateTime and add it to the query command (cmd variable).
If this dosen't work, double check your table structure if it's in DateTime format.
Do a manually insert directly in database via SQL Server Management Studio.
I had the same problem before. I fixed it by deleting the corresponding columns in the data base and recreate it with the correct format "so date time for you". problem was fixed.
it seems there is still information in the data base telling what format it was before.
I have a SQL Database with the following structure:
I have 4 MaskedTextBox for:
(Structure)
DateFrom: 0000.00.00
DateFromTime: 00:00:00
DateTo: 0000.00.00
DateToTime: 00:00:00
.
SqlCommand cmd = new SqlCommand("INSERT INTO TABELLE2 (MessageHeadline, MessageText, SpecifyUser, CreateDate, CreateTime, CreateUser, DateFrom, DateFromTime, DateTo, DateToTime) VALUES (#MessageHeadline, #MessageText, #SpecifyUser, #CreateDate, #CreateTime, #CreateUser, #DateFrom, #DateFromTime, #DateTo, #DateToTime)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#MessageHeadline", TB_MSGHeadline.Text);
cmd.Parameters.AddWithValue("#MessageText", TB_MSGText.Text);
cmd.Parameters.AddWithValue("#SpecifyUser", TB_SpecifyUser.Text);
cmd.Parameters.AddWithValue("#CreateDate", CreateDate );
cmd.Parameters.AddWithValue("#CreateTime", CreateTime);
cmd.Parameters.AddWithValue("#CreateUser", CreateUser);
cmd.Parameters.AddWithValue("#DateFrom", MTB_DateFrom.Text);
cmd.Parameters.AddWithValue("#DateFromTime", MTB_DateFromTime.Text);
cmd.Parameters.AddWithValue("#DateTo", MTB_DateTo.Text);
cmd.Parameters.AddWithValue("#DateToTime", MTB_DateToTime.Text);
connection.Open();
cmd.ExecuteNonQuery();
TB_MSGHeadline.Clear();
TB_MSGText.Clear();
TB_SpecifyUser.Clear();
And finally I want to save these values from my MasketTextBox into my database to use them later.
I try to change the Structure and try some SQL Date/Time formation but i get the error:
You're passing the DATE parameters in the incorrect format. You need to pass them as a valid DateTime which your MaskedTextBox values do not appear to be.
For example, #DateFrom is a SQL Date data type. You should pass it a valid parameter such as a DateTime:
cmd.Parameters.AddWithValue("#DateFrom", DateTime.Now);
You may need to parse the MaskedTextBox values correct using DateTime.TryParse
DateTime parsedDate;
bool success = DateTime.TryParse(MaskedInputOne.Text, out parsedDate);
if (success) {
cmd.Parameters.AddWithValue("#DateFrom", parsedDate);
}
In this case we are only adding the parameter if the conversion succeeds.
I'm building an application that stores a group of datetimes to keep track of when I print a particular report. The report is built up of information from a second table that also has datetimes. I'm trying to get the report to populate a datagridview with records that are only after the last datetime in the first table.
The first table is called 'deliverylog', this table stores the past print dates. The second table is called 'joblog', and it stores the records of previous job entries.
When I run the program, it works just fine and populates the gridview with all records after the last date, but it's not refined... it only populates with dates after the date and not the time. I need the query to populate the gridview to the second....
DateTime lastDeliveryDate;
private void getLastDelivery() // Sets global variable lastDeliveryDate to the last timestamp entered in the deliverylog table
{
openLogConnection();
try
{
command = new SqlCeCommand("SELECT TOP 1 * FROM deliverylog ORDER BY Id DESC", logConn);
drLogSet = command.ExecuteReader();
while (drLogSet.Read())
{
lastDeliveryDate = Convert.ToDateTime(drLogSet["Timestamp"]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
logConn.Close();
}
}
private void populateGridView()
{
openLogConnection();
try
{
command = new SqlCeCommand("SELECT * FROM joblog WHERE TimeStamp > #date", logConn);
command.Parameters.AddWithValue("#date", lastDeliveryDate);
dtLogSet = new DataTable();
bsLogSet = new BindingSource();
daLogSet = new SqlCeDataAdapter(command);
cbLogSet = new SqlCeCommandBuilder(daLogSet);
daLogSet.Fill(dtLogSet);
bsLogSet.DataSource = dtLogSet;
dataGridView1.DataSource = bsLogSet;
dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
logConn.Close();
}
}
Anyone know how to get the this working right? I'm storing the timestamps for both tables as datetime data types and in the following format: "MM/dd/yyyy hh:mm:ss tt"
I believe that using the AddWithValue method is internally converting the value and probably loosing the desired time precision. Instead, use the Add(String, SqlDbType) method overload of the Parameters collection:
var dateParameter = command.Parameters.Add("#date", SqlDbType.DateTime);
dateParameter.Value = this.lastDeliveryDate;
Make sure you have the correct value before setting the parameter value by inspecting the variable using the debugger.
And you could try using the DATEDIFF SQL function instead of the > operator to ensure proper precision:
SELECT * FROM joblog WHERE DATEDIFF(second, #date, TimeStamp) > 0
The problems is probably this line:
lastDeliveryDate = Convert.ToDateTime(drLogSet["Timestamp"]);
Assuming your TimeStamp field is a datetime type, you should use:
lastDeliveryDate = (DateTime) drLogSet["TimeStamp"];
Please confirm the data type of your TimeStamp field.
You should format the date to yyyyMMdd hh:mm:ss.
lastDeliveryDate.toString("yyyyMMdd hh:mm:ss").
In this postare more details.
How to compare sqlite TIMESTAMP values
How to convert C# datetime to MySql Datetime format. I am getting value from text box like 7/27/2011 this format. But i want to convert in this format 2011-7-27. So here i am stuking. Please help me. My objective is to filter the record between two dates and show in a listview control in asp.net.
Here is my code:
DateTime dt1 = Convert.ToDateTime(txtToDate.Text);
DateTime dt2 = Convert.ToDateTime(txtFromDate.Text);
lvAlert.DataSource = facade.GetAlertsByDate(dt1, dt2);
lvAlert.DataBind();
I haven't used MySQL with .NET, but Oracle has similar date conversion issues with .NET. The only way to stay snae with this has been to use parameters for date values, both for input as welll as for WHERE clause comparisons. A parameter created with a MySQL date parameter type, and just giving it a .NET datetime value, should work without needing you to do conversions.
EDITED TO ADD SAMPLE CODE
This code sample shows the basic technique of using parameters for DateTime values, instead of coding conversions to text values and embedding those text values directly in the SQL command text.
public DataTable GetAlertsByDate(DateTime start, DateTime end)
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(
"SELECT * FROM Alerts WHERE EventTime BETWEEN #start AND #end", conn);
DataTable table = new DataTable();
try
{
SqlParameter param;
param = new SqlParameter("#start", SqlDbType.DateTime);
param.Value = start;
cmd.Parameters.Add(param);
param = new SqlParameter("#end", SqlDbType.DateTime);
param.Value = end;
cmd.Parameters.Add(param);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(table);
}
finally
{
cmd.Dispose();
conn.Close();
conn.Dispose();
}
return table;
}
This is SQL Server code, but the technique should be the same for most databases. For Oracle, for example, the only changes would be to use Oracle data access objects, and use ":" in place of "#" in parameter names. The technique for MySQL should also be very similar.
For many databases, shortcuts may exist for creating parameters, such as:
cmd.Parameters.AddWithValue("#start", start);
This works when you know the value is not null, and the correct parameter type can be derived from the C# type of the value. "AddWithValue" is specific to SQL Server; "Add" works also but is obsolete in SQL Server.
Hope this helps.
You can assign format to data time, DateTime.ParseExact() or DateTime.ToString(format), :
the format for 2011-7-27 is yyyy-m-dd
Assuming you are doing this in the database I think you should use date_format to get in the required format
Something like date_format(dateval,'%Y-%c-%d') (Not tested)
I use:
string fieldate = dt1.ToString("yyyy-MM-dd");