My problem specifically is I can't filter by a Date field.
Here is my code:
string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\Tools;Extended Properties=dBASE IV;User ID=Admin;Password=;";
using (OleDbConnection con = new OleDbConnection(connstr))
{
string sql = "select USERNUMBER,FIRSTNAME,LASTNAME, LASTACCESS from EMP WHERE TERMINATED=\"Y\" AND [LASTACCESS]<\"2001/10/20\"";
OleDbCommand cmd = new OleDbCommand(sql, con);
con.Open();
OleDbDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
It works fine if I omit the date field. I just can't figure out what the format is. If I look at the table with a dbf viewer utility the LASTACCESS field is in dd.mm.yyyy (with the periods as separators, but I don't know if that is just a behavior of the utility).
If I omit the forward slashes from the date field, it works but returns zero records (even though I know there are).
Try this and forget date time hell
string sql = "select USERNUMBER,FIRSTNAME,LASTNAME, LASTACCESS from EMP WHERE TERMINATED=\"Y\" AND [LASTACCESS]<#StartDate";
OleDbCommand cmd = new OleDbCommand(sql, con);
cmd.Parameters.AddWithValue("#StartDate", new DateTime(2001, 10, 20));
Just use parameters and forget about formatting them yourself .
The framework is here to help you and provide solutions already tested and working like a charm
Related
I am trying with oracle database to Insert and select Hebrew letters
and it not working well.
I tried
Insert into mytable values ('היי');
and the result is ??? and not היי
can someone help me with that
Edit:
Now after i ask from DBA for hebrew option i can write in Hebrew from the sqlplus
but now from my project it still write ???
my code is
OleDbConnection conn = Connect();
conn.Open();
OleDbCommand com = new OleDbCommand("Insert into mytable values ('היי')", conn);
com.ExecuteNonQuery();
and still the result is ???
I can't really test this because I don't know anything about your database (not even your column names), but you should do that command with parameters:
var testString = "היי"; // Do be aware that Visual Studio displays Hebrew text right-to-left, so the actual string is reversed from what you see.
using (OleDbConnection conn = Connect())
{
conn.Open();
using (OleDbCommand com = conn.CreateCommand())
{
// OleDbCommand com = new OleDbCommand("Insert into mytable values ('היי')", conn);
com.CommandText = "Insert into mytable values (?)";
com.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.VarWChar }).Value = testString;
com.ExecuteNonQuery();
}
}
Also, don't forget to dispose your disposables via a using statement.
Relatedly, here is a report that using a parameterized query fixed a similar problem with OracleCommand.
I am a beginner at C# .net and my question is about creating a program in C# which shows the result from a small database for each date selected from month calendar. For example I choose 25/5/2013 and it shows in a richtextbox appointment with john smith.
I get the date with
this.richTextBox1.Text = monthCalendar1.SelectionRange.Start.Date.ToShortDateString();
but when I try to show the row I want, the program crashes. I used this code to show it in datagrid
SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=event_agenda;Integrated Security=True");
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("Select * from event where date_event =" + monthCalendar1.SelectionRange.Start.Date.ToShortDateString(), conn);
SDA.Fill(dt);
dataGridView1.DataSource = dt;
it doesn't show anything
But with this it shows all rows in database without problem
SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=event_agenda;Integrated Security=True");
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("Select * from event", conn);
SDA.Fill(dt);
dataGridView1.DataSource = dt;
My database has a table event and two columns: date_event (varchar(9)) and notes (varchar(150))
Where is my mistake? I would appreciate if someone helps me
First thing. You should never represents dates with strings in database.
So I really suggest you to change that field to a DateTime column
Second, your query fails because you pass a string without using quotes around it
Let me show how to do it correctly (after changing your column to a datetime)
DateTime mDate = monthCalendar1.SelectionRange.Start.Date;
SqlDataAdapter SDA = new SqlDataAdapter("Select * from event where date_event=#dt", conn);
SDA.SelectCommand.Parameters.AddWithValue("#dt", mDate);
SDA.Fill(dt);
This code use a parameterized query. The placeholder #dt in the query text will be handled by the Framework code using the value assigned to the parameter named #dt.
This parameter is added to the parameter collection of the SelectCommand used by the SqlDataAdapter to retrieve your data.
In this way you don't have to worry how to represent (format as a string) a date and you avoid the risk of Sql Injection
If you really insist in using a string to represent a date (a very bad practice that will do nothing good to your program in the long run) you could simply add, as value, the string representation of the date extracted by your calendar.
I suggest you should change the table column to date. Then, in your code, you may format the date as follows:
var d = monthCalendar1.SelectionRange.Start.Date;
var formattedDate = d.ToString("yyyyMMdd");
You query would look like:
SqlDataAdapter SDA =
new SqlDataAdapter("Select * from event where date_event ='" + formattedDate + "'", conn);
I have the following code which tries to store e values form 3 textboxes into a MS Access 2007 database.
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\dxs.accdb");
string SqlString = "Insert Into tests( [Nam], [add], [phone]) Values (?,?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue(#"Nam", textBox1.Text);
cmd.Parameters.AddWithValue(#"add", textBox2.Text);
cmd.Parameters.AddWithValue(#"phone",textBox3.Text);
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("entered");
}
}
But even though the code is correct after entering values nothing is being stored in table.
Shouldn't
cmd.Parameters.AddWithValue(#"Nam", textBox1.Text);
Be:
cmd.Parameters.AddWithValue("#Nam", textBox1.Text);
And so on for the other parameters?
When i had the similar problems, solution was:
If database is part of application it can be copied in a bin folder - and then application work with it. That is why you can`t find your changes in datatables with MS Access client.
Make sure your database exists in output(bin) folder where exists your exe file of project. If not then copy it there. After your have your database file at right place, You will be to see the changes.
Additionally, you also need few changes in your code, you have problem with your parameter.
Change Values (?,?,?) to Values (#Nam,#add,#phone)"; and #"Nam" to "#Nam". See the comments Correction1 and Correction2.
Also no need to use double slash \\ when you are using # at beginning of string
string ConnString=#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\dxs.accdb");
string sql="Insert Into tests([Nam],[add],[phone]) Values (#Nam,#add,#phone)";
// Correction 1: Above line is changed ?,?,? to parameter names (names used by your command)
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Nam", textBox1.Text);
cmd.Parameters.AddWithValue("#add", textBox2.Text);
cmd.Parameters.AddWithValue("#phone",textBox3.Text);
// Correction 2: your parameter names are changed #"xyz" to "#xyz"
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("entered");
}
}
your insert statement should be like dis
string SqlString = "Insert Into tests( [Nam], [add], [phone]) Values (#Nam, #add, #phone)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Nam", textBox1.Text);
cmd.Parameters.AddWithValue("#add", textBox2.Text);
cmd.Parameters.AddWithValue("#phone",textBox3.Text);
try this
OLEDB can be used to read and write Excel sheets. Consider the following code example:
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\my\\excel\\file.xls;Extended Properties='Excel 8.0;HDR=Yes'")) {
conn.Open();
OleDbCommand cmd = new OleDbCommand("CREATE TABLE [Sheet1] ([Column1] datetime)", conn);
cmd.ExecuteNonQuery();
cmd = new OleDbCommand("INSERT INTO Sheet1 VALUES (#mydate)", conn);
cmd.Parameters.AddWithValue("#mydate", DateTime.Now.Date);
cmd.ExecuteNonQuery();
}
This works perfectly fine. Inserting numbers, text, etc. also works well. However, inserting a value with a time component fails:
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\my\\excel\\file.xls;Extended Properties='Excel 8.0;HDR=Yes'")) {
conn.Open();
OleDbCommand cmd = new OleDbCommand("CREATE TABLE [Sheet1] ([Column1] datetime)", conn);
cmd.ExecuteNonQuery();
cmd = new OleDbCommand("INSERT INTO Sheet1 VALUES (#mydate)", conn);
cmd.Parameters.AddWithValue("#mydate", DateTime.Now); // <-- note the difference here
cmd.ExecuteNonQuery();
}
Executing this INSERT fails with an OleDbException: Data type mismatch in criteria expression.
Is this a known bug? If yes, what can be done to workaround it? I've found one workaround that works:
cmd = new OleDbCommand(String.Format(#"INSERT INTO Sheet1 VALUES (#{0:dd\/MM\/yyyy HH:mm:ss}#)", DateTime.Now), conn);
It basically creates an SQL statement that looks like this: INSERT INTO Sheet1 VALUES (#05/29/2011 13:12:01#). Of course, I don't have to tell you how ugly this is. I'd much rather have a solution with a parameterized query.
It appears to be a known bug https://connect.microsoft.com/VisualStudio/feedback/details/94377/oledbparameter-with-dbtype-datetime-throws-data-type-mismatch-in-criteria-expression
You might want to truncate the milisecond like this it appear to work for OleDbParameter:
DateTime org = DateTime.UtcNow;
DateTime truncatedDateTime = new DateTime(org.Year, org.Month, org.Day, org.Hour, org.Minute, org.Second);
And add this instead of the DateTime.Now into your parameter value.
The problem is the cell containing datetime value cannot be directly put into excel' column. You have to either insert the date component or the time component. The reason for failure is the default property of excel' cell is "values" instead of "datetime" in excel.
I am using OLEDB to Update data in .dbf database from c#.
I get Error: System.Data.OleDb.OleDbException {"Undefined function 'replace' in expression."} on ExecuteNonQuery.
How can I make this work with least changes, i need to replace double quotes with single quotes in many files, so i have to automate this process.
Should I try ODBC or something else for .dbf database?
Help please!
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + directory +";Extended Properties=dBASE III;";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "update Addres_1 set NAME_ENU = replace(NAME_ENU, 'a', 'b') where NAME_ENU like '*a*'";
int res = cmd.ExecuteNonQuery();
Replace is not supported by used data provider.
I will update answer if and when i find out how to do this in fast and simple way on large dataset.