I am using ms access as database that contains field identified as (short date)
i inserted time to that field from datetimepicker in C# using the following query:
string query = #"insert into category_in (category_id,amount_in,dates)
values ('" + ids + "','" + amount2 + "','"+dateTimePicker1.Text+"')";
and everything is ok. But when i am trying to compare the date in the database with date from another datetimpicker it doesnot work. This is the query of comparsion:
query = "SELECT products.category, category_in.dates FROM products, category_in where " +
"category_in.dates>= " + dateTimePicker1.Value.Date.ToShortTimeString() + " "
"and category_in.dates<= " + dateTimePicker2.Value.Date.ToShortTimeString() + "";
when i use dateTimePicker.value.Date it gives me the following error
Syntax error (missing operator) in query expression
'category_in.dates>= 16/08/2015 12:00:00 ص and category_in.dates<=
20/08/2015 12:00:00 ص
but when i add dateTimePicker.value.Date.ToShortTimeString no results returned although there are some data between these dates
do i have to change the insertion method?
I'm surprised that all three answers (so far) have suggested that you continue using dynamic SQL and fiddle with your string-formatted dates and delimiters until you get something that works.
That's just dumb.
The DateTimePicker control returns a System.DateTime value so you should just use that as part of a parameterized query, something like this:
using (var conn = new OdbcConnection(
#"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
#"Dbq=C:\Users\Public\Database1.accdb"))
using (var cmd = new OdbcCommand("INSERT INTO MyTable (DateTimeField) VALUES (?)", conn))
{
conn.Open();
cmd.Parameters.Add("?", OdbcType.DateTime).Value = dateTimePicker1.Value.Date;
cmd.ExecuteNonQuery();
}
I think your code should use the # delimiter for date expressions in Access:
string query = #"insert into category_in (category_id,amount_in,dates)
values ('" + ids + "','" + amount2 + "',#" + DateTime.Parse(dateTimePicker1.Text).ToString("yyyy'/'MM'/'dd") + "#)";
and:
query = "SELECT products.category, category_in.dates FROM products, category_in where " +
"category_in.dates >= #" + dateTimePicker1.Value.Date.ToString("yyyy'/'MM'/'dd") + "# "
"and category_in.dates <= #" + dateTimePicker2.Value.Date.ToString("yyyy'/'MM'/'dd") + "#";
Try changing your query to this:
query = "SELECT products.category, category_in.dates FROM products, category_in where " +
"category_in.dates>= #" + dateTimePicker1.Value.ToShortDateString() + "# "
"and category_in.dates<= #" + dateTimePicker2.Value.ToShortDateString() + "#";
The issue is your dates are strings. Add Single quotes before and after your datetime values. Like this...
query = "SELECT products.category, category_in.dates FROM products, category_in where " +
"category_in.dates>= '" + dateTimePicker1.Value.Date.ToShortTimeString() + "' "
"and category_in.dates<= '" + dateTimePicker2.Value.Date.ToShortTimeString() + "'";
This will allow the query engine to implicitly convert the strings to datetimes.
Related
I am getting an error
ERROR [42500] ERROR: 3020 - There was an error when converting the date value "0000-00-48. In the field "salesOrder Transaction Date
The date value I am trying to insert is 4/4/2018.
My code
DateTime JobDate = Wintac_JobDate;
string addSalesOrder = "INSERT INTO SalesOrderLine (CustomerRefListID, TemplateRefListID," +
" SalesOrderLineItemRefListID, SalesOrderLineDesc,SalesOrderLineQuantity, SalesOrderLineRate, " +
"SalesOrderLineSalesTaxCodeRefListID, Memo, SalesOrderLineInventorySiteRefListID, SalesOrderLineInventorySiteLocationRefListID" +
", TxnDate, ShipAddressAddr1, ShipAddressAddr2, ShipAddressAddr3, ShipAddressAddr4, ShipAddressAddr5, FQSaveToCache)" +
"VALUES('" + QBCustomerListID + "','" + templateLID + "', '" + LID + "', '" + Description + "', " + Quantity + ", " + 120 + "," +
" '" + SalesTax + "', '" +Wintac_WipNo+"','"+LaborSite+"','"+LaborSiteLocation+"',"+
"?,'" + shipAdr1+ "','" + shipAdr2 + "','" + shipAdr3 + "','" + shipAdr4 + "','" + shipAdr5 + "'," +
""+ FQSaveToCache + ")";
OdbcCommand sqlcmd2 = new OdbcCommand(addSalesOrder, quickbookscon2);
sqlcmd2.CommandType = CommandType.Text;
sqlcmd2.CommandTimeout = 180;
MessageBox.Show(JobDate.ToShortDateString());
sqlcmd2.Parameters.Add("P7", OdbcType.DateTime).Value = JobDate
if (Quantity != 0)
{
if (sqlcmd2.ExecuteNonQuery() == 1)
{
if(FQSaveToCache == 0)
MessageBox.Show(" added successfully.");
}
}
sqlcmd2.Dispose()
I have tried converting the variable Job Date
Date Time
short date string
long date string
entering the variable directly into the query
Any help would be appreciated.
I think the main problem is on that line;
sqlcmd2.Parameters.Add("P7", OdbcType.DateTime).Value = JobDate.ToLongDateString()
You try to insert string representation on a DateTime typed column. That's quite wrong. You need to directly pass your DateTime value instead of passing it string representation. To learn this as a habit, please read Bad habits to kick : choosing the wrong data type
Other than this, I saw a few problem also in your code:
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Use using statement to dispose your connection and commmand automatically instead of callind Dispose method manually which you didn't even consider to do in your code.
So i am trying to delete data in database based on two things.
First is a combox box which selects the column name and second is the value whose row is to be deleted.
(#"SELECT * FROM Contacts WHERE " + var + " LIKE " + textBox1.Text + ";");
Now the problem here is that as long as the value in the textBox is numerical this query will work fine. However if it is a string value the query will fail because i haven't inserted the single quote.
Is there anyway i can make just a single unified query for handling both numerical and text data.
Okay, let's not do this. We need to just use parameters.
(#"SELECT * FROM Contacts WHERE " + var + " LIKE #" + var + ";");
...
cmd.Parameters.AddWithValue("#" + var, textBox1.Text);
So the overall code might look something like this:
string varName = string.Format("#{0}", var);
string sql = string.Format("SELECT * FROM Contacts WHERE {0} LIKE #{0}", var);
using (SqlConnection c = new SqlConnection(cString))
using (SqlCommand cmd = new SqlCommand(sql, c))
{
cmd.Parameters.AddWithValue(varName, textBox1.Text);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
}
Also, have a look at this post on my blog. It talks about what I just went through, as well as how to safely do a LIKE.
Try using parameterized query
SqlCommand command = new SqlCommand(
#"SELECT * FROM Contacts WHERE " + var + " LIKE #param", connection));
command.Parameters.AddWithValue("#param", textBox1.Tex);
You need to add quotes arounf the value so that it will accept string as well numerical values
(#"SELECT * FROM Contacts WHERE " + var + " LIKE '" + textBox1.Text + "';");
How about this:
(#"SELECT * FROM Contacts WHERE " + var + " LIKE " _
+ iif(isnumeric(textBox1.Text),textbox1.text, "'" +textbox1.text +"'" + ";");
That's a vb-centric IIF statement, but there's an equivolent in C#.
(#"SELECT * FROM Contacts WHERE " + var + " LIKE '" + textBox1.Text + "';");
U can check the value whether its integer or string and format different query accordingly.U can use like operator also.
String str = Console.ReadLine();
int myval;
String query="";
if(int.TryParse(str,out myval))
query=#"SELECT * FROM Contacts WHERE " + var + " LIKE " + myval + ";";
else
query=#"SELECT * FROM Contacts WHERE " + var + " LIKE '" + str + "';";
I have a problem working on my project.
I'm trying to read a data from an Excel file. It works fine when I'm trying to select rows which are greater than Col1Value but after I add AND Gender = " + gender; it gives me error "NO VALUE GIVEN FOR ONE OR MORE REQUIRED PARAMETERS" I cannot set a specific gender column because It is different on every excel file although column name is same and error appears when I'm trying to fill the DataSet.
if (boxGender.Text != "")
string gender = boxGender.Text;
string col1Name = lbl1stColumn.Text;
string Query = "select * from [data$] where " +
col1Name + " > " + Col1Value +
" AND Gender = " + gender;
OleDbDataAdapter dacol1 = new OleDbDataAdapter(Query, con);
Column1Data.Clear();
dacol1.Fill(Column1Data)
lblStuCount1Col.Text = Column1Data.Tables[0].Rows.Count.ToString();
You need to enclose the string value in single quotes and the column names in square brackets:
string Query = "select * from [data$] where [" +
col1Name + "] > " + Col1Value +
" AND Gender = '" + gender + "'";
I think you might be missing quotes in your SQL query:
string Query = "select * from [data$] where " + col1Name + " > '" + Col1Value + "' AND Gender = '" + gender +"'";
Note single quote (') symbols added.
I am trying to wirte an sql statement such that I can either update (if record already exists) or insert a data record into an access db via an OleDBCommand.
sql statement:
string sql = "IF EXISTS (SELECT * FROM tblMitarbeiter_Arbeitsform WHERE (fkLogin = '" + _Login.ToUpper() + "') AND (fkIdArbeitsform = " + dr.fkIdArbeitsform + "))";
sql += " UPDATE tblMitarbeiter_Arbeitsform SET (Prozent = " + dr.Prozent + ")";
sql += " WHERE (fkLogin = '" + _Login.ToUpper() + "') AND (fkIdArbeitsform = " + dr.fkIdArbeitsform + ")";
sql += " ELSE INSERT INTO tblMitarbeiter_Arbeitsform (fkLogin, fkIdArbeitsform, Prozent) VALUES ('" + _Login.ToUpper() + "', " + dr.fkIdArbeitsform + ", " + dr.Prozent + ")";
oCmd = new OleDbCommand(sql, getOekobonusConnection());
oCmd.ExecuteScalar();
//oCmd.ExecuteNonQuery();
both ExecuteScalar and ExecuteNonQuery are not working. What am I doing wrong?
There's no control of flow constructs in Access SQL so you can't do an IF. You would have to split the logic and do the test in your code, then issue an update or insert accordingly.
I am new to programming and is developing a new desktop database applcation in Access, I am trying to insert data into a table. I had two datetime picker and I read the value from it as
jobcodedatabean.PaperRecievedate1 = dtpjobcodedate.Value.Date;
jobcodedatabean.Shipmenentdate = dtpshipmentdate.Value.Date;
and I had passed the databean to a function
public void addaction(JobCodeDataBean jobcodedatabean)
{
MessageBox.Show(jobcodedatabean.Shipmenentdate.ToString());
try
{
OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(connString);
oleDbConnection1.Open();
OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("INSERT INTO jobcodemastertable (jobcode ,customercode,totaltrip,shipmentdate,fromPlace, destination,description ,packagetype ,noofpackage ,contactperson ,jobecodedate ) Values ('" + jobcodedatabean.Jobcode + "', '" + jobcodedatabean.Customercode + "' ," + jobcodedatabean.Totaltrip + "," + jobcodedatabean.Shipmenentdate + " ,'" + jobcodedatabean.Fromplace + "','" + jobcodedatabean.Destination + "','" + jobcodedatabean.Description + "','" + jobcodedatabean.Typeofpackage + "','" + jobcodedatabean.Noofpackages + "','" + jobcodedatabean.Contactperson + "'," + jobcodedatabean.PaperRecievedate1 + ") ", oleDbConnection1);
oleDbCommand1.CommandType = CommandType.Text;
oleDbCommand1.ExecuteNonQuery();
oleDbConnection1.Close();
}
catch (Exception)
{
MessageBox.Show(e);
}
but i am getting the exception at the query
Syntax error (missing operator) in query expression '2/16/2012 12:00:00 AM'.
In access the date fields are in short date format
Please somebody help to sort out my mistake
Incorrect quotations. To avoid these kinds of mistakes, use ordered parameters:
var myCommand = new OleDbCommand(
"INSERT INTO MyTable(someDateField, someTextField, someNumberField) VALUES (?, ?, ?)"
);
myCommand.Parameters.Add(DateTime.Now);
myCommand.Parameters.Add("Some text");
myCommand.Parameters.Add(123);
Using parameters also helps protect against SQL injection attacks. In your example, if one of the strings contained an apostrophe, it would fail unless you correctly converted it to two apostrophes. With parameters these are escaped correctly automatically.
You forgot to enclose dates in quotes:
... ",'" + jobcodedatabean.Shipmenentdate + "' ,'" ...
... "','" + jobcodedatabean.PaperRecievedate1 + "') " ...
Note single quotes around both dates.