Visual studio 2008 datetimepicker to oracle date and timestamp - c#

im trying to insert data into my oracle database but i am getting "invalid month" error as
it seems that i cant convert the datetimepicker value of my form into oracle date or timestamp(7) please help!
my code
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = " dd MM yyyy ";
string m = "insert into member(memberid,name,street,roadno,houseno,phoneno,joindate,sex) values(member_deptno.nextval,'" + a + "','" + b+ "','" + c + "','" + d + "','" + h + "','" + dateTimePicker1.Value.Date+ "','"+de+"')";

user parameterized sql insert.
e.g. parameterized select query
SqlConnection objConnection = new SqlConnection(connectionString);
objConnection.Open();
SqlCommand objCommand = new SqlCommand(
"SELECT * FROM User WHERE Name = #Name AND Password = #Password",
objConnection);
objCommand.Parameters.Add("#Name", tbName.Text);
objCommand.Parameters.Add("#Password", tbPassword.Text);
SqlDataReader objReader = objCommand.ExecuteReader();

As others have mentioned parameters are the way to go but I don't think they'll solve your issue.
I assume the CustomFormat shown in your snippet is the format Oracle wants. The problem is that when you call dateTimePicker1.Value.Date it gives you a DateTime object and since you're combining it with a string it executes the .ToString() method which results in a different format. You should put your format string in the .ToString() to control the output. Example:
dateTimePicker1.Value.Date.ToString("dd MM yyyy");

Related

Reading string as date from csv files in c# Windows Application

I'm exporting a CSV file into a datatable. Exporting is working fine. The provider using is Microsoft.ACE.OLEDB.12.0
The issue is that I have a column with date which contains date in string along with single quots, I removed the single quote, the date format is like this: "2015-05-02 12:57:43.888"
I need to convert this date to dd/MM/yyy format.
I tried using convert function, but it's showing error
Undefined function convert in expression
Since I need to filter the csv file based on date, I need to convert the date from csv itself.
My code is as follows:
string header = isFirstRowHeader ? "Yes" : "No";
string pathOnly = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);
string sql = #"Select * From " +
" (SELECT ['TRANSACT'] AS InvNo,['TIMESTART'] AS InvDate,['STATUS'] AS InvStatus,['NETTOTAL'] AS InvNet ,['FINALTOTAL'] " +
" AS InvFinal,REPLACE(['TIMESTART'],'''','') as TIMESTART FROM [" + fileName + "]) Table1 " +
" WHERE convert(varchar(10),TIMESTART,103) between '" + strFrom + "' and '" + strTo + "'";
using (OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
using (OleDbCommand command = new OleDbCommand(sql, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
adapter.Fill(dataTable);
}
Try using this code:
var sDate = "2015-05-02 12:57:43.888";
DateTime date = new DateTime();
DateTime.TryParse(sDate, out date);
Console.WriteLine(date.ToString("dd/MM/yyyy"));
Or take a look here .NET Fiddle
I found the answer.
Since I'm using the Microsoft.ACE.OLEDB driver to load the csv sheet via Provider=Microsoft.ACE.OLEDB.12.0 I have to use the query formatting and functionality available within MS Access.

How to provide dates in a culture-agnostic way to MS Access OleDb Command?

I'm working on a C# program. In that program, I select some dates from Access 2010 database and process data. But, I can't access and process data on rows containing dates from a range of 01/12/2014 and 11/12/2014 but I can process remaining dates.
cmd = new OleDbCommand("SELECT MIN([Vch No]) FROM [" + group + "] WHERE [Entry Date]=#" + date + "#", conn);
long Vch = long.Parse(cmd.ExecuteScalar().ToString()) - 1;
I get error on line long Vch = ... - 1; saying can't get proper Input string. Whereas, it works for other dates either before or after these particular dates.
I declare the date by this code :
cmd = new OleDbCommand("SELECT TOP 1 * FROM (SELECT DISTINCT [Entry Date] FROM [" + group + "]) WHERE [Entry Date]>#" + initDate + "# ORDER BY [Entry Date]", conn);
dr = cmd.ExecuteReader(); dr.Read();
string date = dr["Entry Date"].ToString();
Thank you in advance!
Try setting you date variable to a non culture specific date format, so YYYY/MM/DD e.g. 2014/12/01
If date is a C# DateTime object, you'll need to call:
date.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
As per convert datetime to yyyy/MM/dd
So:
cmd = new OleDbCommand("SELECT MIN([Vch No]) FROM [" + group + "] WHERE [Entry Date]=#" +
date.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture) +
"#", conn);
long Vch = long.Parse(cmd.ExecuteScalar().ToString()) - 1;
EDIT TO ADD
As per #Gord-Thompson's comment, it's always considered best practise to use parameters where ever possible (generally always!).
So:
cmd = new OleDbCommand("SELECT MIN([Vch No]) FROM [#pGroup] WHERE [Entry Date]=#pDate", conn);
cmd.Parameters.Add("#pGroup", OleDbType.NVarChar).Value = group;
cmd.Parameters.Add("#pDate", OleDbType.DateTime).Value = date;
long Vch = long.Parse(cmd.ExecuteScalar().ToString()) - 1;
Try to avoid using cmd.Parameters.AddWithValue() - see http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/ for more details.

C# Mysql select Date(yyyy/mm/dd) from column by month value (12)

I am trying to figure out the way to sum values of certain columns. How do I get Date month value from Date column where all values are in date (yyyy/mm/dd) format?
What I should write in :
WHERE Data = '"?????"' ";
I want to pick up date where month equals 12.
Here is my code :
MySqlConnection cnn = new MySqlConnection(connectionString);
cnn.Open();
string query = "select sum(SUMA) from `nuolatines pajamos` WHERE ID = '" + perdavimo1.id_permetejas.ToString() + "' WHERE Data = '"+ now.Month +"' ";
MySqlCommand createCommand = new MySqlCommand(query, cnn);
var sum = createCommand.ExecuteScalar().ToString();
nl_pajamos.Text = sum.ToString();
DateTime.Parse(stringobject,cultureinfo);
for example
DateTime.Parse("20-01-2014",new CultureInfo("nl-BE

Unable to insert DateTime format into database

I'm unable to insert the DateTime into my database. Am i writing the statement wrongly?
Apparently without the DateTime, I am able to insert into the database
string dateAndTime = date + " " + time;
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime theDateTime = DateTime.ParseExact(dateAndTime, "d MMMM yyyy hh:mm tt", provider);
//Create a connection, replace the data source name with the name of the SQL Anywhere Demo Database that you installed
SAConnection myConnection = new SAConnection("UserID=dba;Password=sql;DatabaseName=emaDB;ServerName=emaDB");
//open the connection
; myConnection.Open();
//Create a command object.
SACommand insertAccount = myConnection.CreateCommand();
//Specify a query.
insertAccount.CommandText = ("INSERT INTO [meetingMinutes] (title,location,perioddate,periodtime,attenders,agenda,accountID,facilitator,datetime) VALUES ('"+title+"','" + location + "', '" + date + "','" + time + "', '" + attender + "','" + agenda + "', '" + accountID + "','" + facilitator + "','" +theDateTime+ "')");
try
{
insertAccount.ExecuteNonQuery();
if (title == "" || agenda == "")
{
btnSubmit.Attributes.Add("onclick", "displayIfSuccessfulInsert();");
//ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Please ensure to have a title or agenda!');", true);
}
else
{
btnSubmit.Attributes.Add("onclick", "displayIfSuccessfulInsert();");
Response.Redirect("HomePage.aspx");
//ScriptManager.RegisterStartupScript(this, this.GetType(), "Redit", "alert('Minutes Created!'); window.location='" + Request.ApplicationPath + "/HomePage.aspx';", true);
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
finally
{
myConnection.Close();
}
It does not insert the SQL into my database.
PS: theDateTime for example, may a value which is 7/14/2012 1:35:00 AM. How to insert this into the database??
Yes, you should write the query with parameters {0}, {1}, etc, and then use Parameters.Add.
insertAccount.CommandText = ("INSERT INTO [meetingMinutes]
(title,location,perioddate,periodtime, ...)
VALUES (?,?,?,?, ... )");
insertAccount.Parameters.Add( ... );
This will ensure that the SQL gets formed with correct syntax; and also prevent SQL injection attacks.
First of all NEVER use string concatenation for SQL queries or commands. Use parameters.
If you will use parameters then:
it is not possible to make sql-injection
query text and plan is cached, which increases performance
and what is important in your case - you do not have to think about formatting of the value, just pass the DateTime variable as the parameter
And also crosscheck that your DB column has datetime2 type, otherwise most likely you will not be able to store values less than 1 Jan 1758 (e.g. DateTime.MinValue).
Dont use quotes for yr date, remove all quotes where you are using a date
change ,'" +theDateTime+ "') to ," +theDateTime+ ")
and also secure yr sql cause it unsave for SQL injections

how to insert a date from textbox to database

please help me to insert a date from a text box in dd-mm-yyyy format to sql server.
my code is as follows:-
int prio = Convert.ToInt32(Priority.Text);
string stdate = planstart.Text;
string endate= planend.Text;
string actst = actualstart.Text;
string acten = actualend.Text;
SqlConnection myconnection = new SqlConnection(constring);
SqlCommand mycommand = new SqlCommand();
DataSet mydataset = new DataSet();
SqlDataAdapter mydataadapter = new SqlDataAdapter();
myconnection.Open();
mycommand.Connection = myconnection;
mycommand.CommandText = " insert into project_status.dbo.Project_Status_Report values('" + projectcode.Text + "','" + projectname.Text + "',(select P_Code from project_status.dbo.Project_Type where Project_Type = '" + projecttype.Text + "')," + prio + ",'" + stdate + "','" + endate + "','" + actst + "','" + acten + "','" + currentstatus.Text + "','" + remark.Text + "','no');";
mycommand.CommandType = CommandType.Text;
mycommand.ExecuteNonQuery();
and it is throwing an exception saying:-
Conversion failed when converting date and/or time from character string.
You need to convert data according to you sql server formate that way you can resolve issue ..
Try
String UrDate = "27/12/2011";
System.Globalization.DateTimeFormatInfo dateInfo = new System.Globalization.DateTimeFormatInfo();
dateInfo.ShortDatePattern = "dd/MM/yyyy";
DateTime validDate= Convert.ToDateTime(toDate, dateInfo);
or
Format String For Dates
// String to DateTime
String MyString;
MyString = "1999-09-01 21:34 PM";
//MyString = "1999-09-01 21:34 p.m."; //Depends on your regional settings
DateTime MyDateTime;
MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt",
null);
Make use of Paramerize query to avoid SQL INJECTION...make code less error pron
Walkthrough: Displaying Data in a Windows Form Using a Parameterized Query
Just a word of caution - you need to sanitize that query to prevent SQL injection attacks. Consider using parameterised queries. Read up about it, it's not really the scope of this answer.
You should create strongly typed DateTime objects first and then format them the way you need to insert. Consider the following modification to your code:
string stdate = DateTime.Parse(planstart.Text).ToString();
string endate = DateTime.Parse(planend.Text).ToString();
string actst = DateTime.Parse(actualstart.Text).ToString();
string acten = DateTime.Parse(actualend.Text).ToString();
EDIT
I removed the string parameter from the ToString() so you can get a valid DateTime string that's usable by SQL Server.
con.Open();
string query = "insert_demo";
/* date fromat Stored*/
TextBox2.Text = DateTime.Now.ToLongDateString();
SqlCommand com = new SqlCommand(query, con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", TextBox1.Text.ToString());
com.Parameters.AddWithValue("#Date", TextBox2.Text.ToString());
com.ExecuteNonQuery();

Categories