Updating Excel Cell with Non-Numeric Data in C# - c#

I have a query that is
ExcelQuery = "Update [Sheet1$] "
+"set CITIZEN_ID = #" + value
+ " where CITIZEN_ID = " + value;
As you can see, I'm essentially just prepending a "#" to the CITIZEN_ID field. value is a int/numeric value. So if I had "256" in the CITIZEN_ID column it would be converted to "#256"
When I execute this I get an OleDbException Syntax error in date in query expression so I surrounded part of the query in single quotes like this,
ExcelQuery = "Update [Sheet1$] "
+"set CITIZEN_ID = '#" + value + "' "
+"where CITIZEN_ID = " + value;
With that I get yet another OleDbException this time with, Data type mismatch in criteria expression.
I'm guessing for some reason the CITIZEN_ID fields don't want to take anything besides a plain number. Is there any way I can remedy this to get that pound symbol in?
Thanks!

Can't you just change the number format so it shows a '#' before each number in the CITIZEN_ID field.
This doesn't solve your stated problem .. but it avoids it :-)
Update:
This StackOverflow Question ( excel-cell-formatting) talks about cell formatting using C#

It sounds like you are trying to use SQL to INSERT a text value into a column which the DBMS (the Access Database Engine) sees as DOUBLE FLOAT and hence getting a type mismatch error. You may be able to change registry values to convince the engine to consider the column to be text, see:
External Data - Mixed Data Types

Related

Generic SQL UPDATE clause suitable for mutliple data types

Fairly new to SQL. Say I have a table with field1 of type string (VARCHAR) and field2 of type integer (INTEGER). As I understand it, you're supposed to use ='newValue' for string fields, and =newValue for integer fields (and =#newValue# for date fields).
Is there a trick that allows generic construction of the SET clause without needing to know the type of the field being updated in advance?
void UpdateDatabase(string field, string oldValue, string newValue)
{
// Construct without needing work out whether '', ## or (nothing) is required?
string sqlUpdate = (
"UPDATE MyTable" +
" SET " + field + " = " + newValue +
" WHERE " + field + " = " + oldValue);
// Execute the statement on the database
}
This might be used as follows:
UpdateDatabase("field1", "Danger Mouse!", "Mickey Mouse");
UpdateDatabase("field2", "15", "7");
Your code will need to be a lot more complex if you want to predetermine the datatypes of the fields you're inserting into.
Most SQL flavours have some kind of catalog, so for example on MS SQL Server you would need do something like:
SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'MyTable' AND COLUMN_NAME = 'field'
For every column you're about to write to, then apply the single-quote or not as per the data type.
There's ways and means of doing this, and depending on how many different fields you want to write at the same time will depend how complex the logic has to be to get the column datatypes.
For a large number of columns ideally you would gather all the column names you're about to write to into a table first, then use that table to query the datatypes
However, in SQL Server you can normally get away with putting single-quotes around everything, even integers and floats. SQL Server will intelligently remove the single quotes as needed.
It looks like you're using MySQL since you're required to put hashes around dates, in which case I am sorry for your loss.

update stock quantity keeping along the previous quantity

I am having problem updating my database with stock. I want to add stock to the previous stock that is available in the inventory but error say that check your mysql Syntax before WHERE. and this is my query.
"UPDATE tblproducts SET Quantity=Quantity+'"+txtAddQty.Text+"' WHERE ProductId='"+txtProductId.Text+"' "
Where am i wrong. Help
You are concatenating Quantity and String (txtAddQty.Text)
"UPDATE tblproducts SET Quantity = Quantity + " + Convert.ToInt32(txtAddQty.Text) +
" WHERE ProductId='" + txtProductId.Text + "'"
Caution
Above SQL Statement fails if txtAddQty.Text gives alphabets instead of numeric value.
Also will fail if txtProductId.Text gives unexpected value
Not recommended way of doing things with database from application.
Instead of making sql statement by string concatenation you should use parametrized sql query. Doing so will prevent some of the sql injection problem.
imho, Quantity=Quantity+'"+txtAddQty.Text+"' will not work.
you need to remove those ' since you would add a varchar to an int
edit: You also could use a debugger to check the output of your string.
I guess Quantity is numeric, so you should remove the apostrophes ' in your string.
And please do not generate SQL-queries with string concatenation.Use parameterized queries: How do I create a parameterized SQL query? Why Should I?
Try removing the single quotes as you are trying to add it as a number. Only use quotes for strings.
Example:
UPDATE tblproducts SET Quantity=Quantity+"+txtAddQty.Text+" WHERE ProductId='"+txtProductId.Text+"' "

Insert date in dd-MM-yyyy format

I'm trying to insert date in dd-MM-yyyy format in c#. Query for inserting is
SqlCommand cmd_cust = new SqlCommand(#"insert into custdetail values ('" + txtInvoiceNo.Text + "','" + txtCustomerName.Text + "','" + txt_contact.Text + "', '" + txtAddress.Text + "', '" + txt_total_amt.Text + "', '" + dt_date.Value.ToString("dd-MM-yyyy") + "')", con_create);
con_create.Open();
cmd_cust.ExecuteNonQuery();
con_create.Close();
I have created table with column name date has datatype date. After inserting record the value in date column field is in yyyy-dd-MM format. I want this in dd-MM-yyyy format.
Do not try to concatenate a string to build a correct sql command.
This leads only to parsing problems and Sql Injection Attacks.
Use instead a parameterized query
int isok = 0;
try
{
// Now your query is more readable and there are no more formatting problems here
SqlCommand cmd_cust = new SqlCommand(#"insert into custdetail values
(#invNo,#custName,#contact,#address,#amount,#dt)",
con_create);
con_create.Open();
cmd_cust.Parameters.AddWithValue("#invNo",txtInvoiceNo.Text );
cmd_cust.Parameters.AddWithValue("#custName",txtCustomerName.Text );
cmd_cust.Parameters.AddWithValue("#contact",txt_contact.Text);
cmd_cust.Parameters.AddWithValue("#address",txtAddress.Text.Text);
// The following parameter could require a conversion if the db field is not of text type
// cmd_cust.Parameters.AddWithValue("#amount", Convert.ToDecimal(txt_total_amt.Text));
cmd_cust.Parameters.AddWithValue("#amount", txt_total_amt.Text);
cmd_cust.Parameters.AddWithValue("#dt",dt_date.Value );
isok= cmd_cust.ExecuteNonQuery();
con_create.Close();
}
Using a parameter you don't need to worry how to format a DateTime value to a string, you pass directly the DateTime value as expected by the database field. It is the framework job to correctly pass this value to the underlying database table.
This is true also for the other fields like the string ones. If your user types a single quote inside one of your textboxes you get a syntax error with the string concatenation. The quote typed by your user mistakenly closes the value leaving the remainder of the text as invalid sql text
(e.g. textCustomerName.Text = O'Brian becomes ....,'O'Brian' ,....)
I agree with Steve's answer above. But, to focus on your specific question, SQL does not store the date in a specific format - it stores it as two integers (in binary). Therefore, the date you see in the query window (or wherever else you are looking at it) does not matter; likewise, whatever format you attempt to insert into the database does not matter (as long as SQL server can parse it correctly). If you want the output to look a certain way, you can re-format to suit your needs on a SELECT query. Both SQL and C# have extensive date formatting methods.
Are you formatting the date in a SQL query output or a C# program output?

Using variables in SQL queries in asp.net (C#)

I have an SQL query of this form
string cmdText = "Select * from " + searchTable
+ "WHERE " + searchTable
+ "Name =' " + searchValue + "'";
Basically what I am trying to do is get a particular actor's info from the database's Actors table. The variable searchTable has the value 'Actor' which is the table name and searchValue has the actor's name (which is represented by the ActorName attribute in the Actor's table, here I am trying to form the name of the attribute by concatenating the words 'Actor' and 'Name' )
So, well, all this concatenation results in (or at least should result in) a query of the form:
Select * from Actor where ActorName ='some actor';
But when I try to run this it gives me the error "Incorrect syntax near '=' " in the browser. Could anyone please help?
You can put (and should!) parameters into your SQL queries for the values in e.g. your WHERE clause - but you cannot parametrize stuff like your table name.
So I'd rewrite that query to be:
SELECT (list of columns)
FROM dbo.Actor
WHERE ActorName = #ActorName
and then pass in just the value for #ActorName.
If you need to do the same thing for directors, you'd have to have a second query
SELECT (list of columns)
FROM dbo.Directors
WHERE DirectorName = #DirectorName
Using parameters like this
enhances security (prohibits SQL injection attacks!)
enhances performance: the query plan for that query can be cached and reused for second, third runs
PS: the original problem in your setup is this: you don't have any space between the first occurence of your table name and the WHERE clause - thus you would get:
SELECT * FROM ActorWHERE ActorName ='.....'
If you really insist on concatenating together your SQL statement (I would NOT recommend it!), then you need to put a space between your table name and your WHERE !
Update: some resources for learning about parametrized queries in ADO.NET:
The C# Station ADO.NET Tutorial / Lesson 06: Adding Parameters to Commands
Using Parameterized Queries with the SqlDataSource
You shouldn't concatenate string to SQL, as this will open you up to SQL Injection attacks.
This is a rather long read about dynamic SQL, but worth reading to understand the risks and options.
You should be using parameterized queries instead, though the only way to use a table name as a parameter is to use dynamic SQL.
I urge you to change your approach regarding table names - this will lead to problems in the future - it is not maintainable and as I mentioned above, could open you to SQL Injection.
The error you are seeing is a result of the concatenation you are doing with the "Where " clause - you are missing a space before it. You are also adding a space after the ' in the parameter ending with "Name".
Your resulting string, using your example would be:
Select * from ActorWHERE ActorName =' some actor';
There is a blank missing and one too much:
searchTable + "Name =' "
should read
searchTable + " Name ='"
Beside that, use SQL parameters to prevent SQL injection.
string cmdText = "Select * from " + searchTable + " WHERE Name = '" + searchValue + "'";

Dynamically taking a table name in aspx form using sql server

I'm trying to dynamically accept a table name depending on the conditions satisfied, also the column name is selected dynamically, and so is the comparison value, but I'm getting an error while running it. I'm writing this code in C# and my backend is SQL server 2005. Please help me.
Here is the code:
if( table=="studenttab")
table = "personal_detail";
thisconnection1.Open();
string p = field[0].ToString().ToLower();
string q = code[0].ToString();
SqlCommand thiscommand3 = thisconnection1.CreateCommand();
thiscommand3.CommandText = " Select * from '" + table + "' where '" + p + "' = '" + q + "' ";
// here it gives error "Incorrect syntax near 'personal_detail'." Dont understand!
SqlDataReader thisreader3 = thiscommand3.ExecuteReader();
To answer your specific question, I would guess the error is due to the fact that you are surrounding your table name and column names with single quotes. your object names should not be surrounded with quotes of any kind.
As a side note, please look into the problems associated with SQL injection attacks. The kind of SQL concatenation you are doing here is widely considered a huge security risk.
Your code is missing several closing braces, a closing quote, and it seems to have misleading indentation.

Categories

Resources