error updating row in postgres table - sql

My table is:
CREATE TABLE A(
id serial NOT NULL,
date timestamp without time zone,
type text,
sub_type text,
filename text,
filepath text,
filesize integer,
);
I have an update routine:
$Query = "UPDATE A SET type=\"" . $strType . "\" where id=" . intval($ID);
Problem:
When $strType is a string, like "lettuce" I get this error:
ERROR: column "lettuce" does not exist
When it is an int, no error.
Ideas?
more background:
the insert code adds filename,filepath, both text types successfully

In SQL, double-quotes are identifier delimiters. Your UPDATE statement is trying to set the type column to the value of the "lettuce" column, which is an error if there is no column named lettuce.
You want to use single-quotes to delimit a string literal in SQL:
$Query = "UPDATE A SET type='" . $strType . "' where id=" . intval($ID);
See also "Do different databases use different name quote?"

Your coding is open to SQL injection. Use placeholders (probably unquoted question marks) and pass the value separately. That avoids the problems at XKCD.
Bill has the answer to your immediate problem about column names vs strings.

Related

How to replace hyphen (dash) in table name?

I have a hive table, where I want to replace the hyphen ('-') with underscore ('_').
The sample query is as:
CREATE TABLE test_${yearAndMonth} ......
INSERT OVERWRITE TABLE test_${yearAndMonth} ......
The 'yearAndMonth' contains value like: 2017-05; So, I want to have the table value name as test_2017_05; however, the 'yearAndMonth' will must contain the hyphen value.
I have tried with: regex replace
For example:
CREATE TABLE test_${regexp_replace(yearAndMonth, '-', '_')} ......
INSERT OVERWRITE TABLE test_${regexp_replace(yearAndMonth, '-', '_')} ......
However, I am getting error as:
cannot recognize input near 'test_' '$' '{' in table name
Any suggestions please.
Update:
Trying in this was way:
CREATE TABLE test_regexp_replace(${yearAndMonth}, "-", "_") ......
INSERT OVERWRITE TABLE test_regexp_replace(${yearAndMonth}, "-", "_") ......
I am getting this error:
missing EOF at '(' near 'test_regexp_replace'
Changing the variable format in hive is not a good idea, try to change the format before passing. Doing something similar to below will work (added id int as a sample column, you can add your own or pass them from another variable if required)
hive --hiveconf table_name=table_$(date '+%Y')_$(date '+%m') -e "create table \${hiveconf:table_name}(id int); insert overwrite table \${hiveconf:table_name}"

How to insert special characters to a table row via SQL Editor

I have a table in my SQL Server database with a column of type nvarchar(50);
I tried to do this:
Right click on my table
Selecting "Edit 200 first rows"
Typing in that column 'a'
I get an error like this:
Error source: .Net SqlClient Data Provider.
Error message: Incorrect syntax near 'a'.
Correct the errors and retry".
Why do I get this error message and how can I fix this?
I have used aqua data studio and tested this it is allowing me.
my result:::
id testc
----- ---------
1 'asdfasd'
If you want to use it thrugh .net then while passing the string add the escape sequences. suppose if you are sending "'"--single quote.. then send I have used and tested this it like "\'" is allowing me.
refer below link:::
http://www.codeproject.com/Questions/157918/How-can-I-insert-a-special-character-in-sql-server
I have had the same error.
I want to insert a value I am Nam 'ABC' into MyTable at field Description as following SQL statement
Insert Into table MyTable (Description) values('I am Nam 'ABC'');
Once Insert command executed the error occur immediately
Incorrect syntax near 'ABC'.
Note that the reason why is SQL will understand character " ' " which before ABC belongs to character
" ' " before I, and one after ABC belongs to " ' " at the end. As a result ABC does not belong to SQL
statement anymore therefore it makes a break of statement.
Here is my solution:
I added two single quotes for each side of ABC
Insert Into table MyTable (Description) values('I am Nam ' 'ABC' ' ');

Access SQL: creating field at runtime

I'm trying to create a "dynamic" field in my SQL query
INSERT INTO tblCARS (CreateField("[tblCARS]","[colors]","TEXT"))
SELECT avail_colors
FROM tblSHOPS
WHERE car_model = model_car;
This should give me the same result as
INSERT INTO tblCARS (colors)
SELECT avail_colors
FROM tblSHOPS
WHERE       car_model = model_car;
The field [colors] does not exist, so i want to append it to the existing table called [tblCARS] when i run the query.
The function CreateField() looks like this
Public Function CreateField(strTable As String, strField As String, strType As String) As Variant
CreateField = Null
If (strField <> vbNullString) And (DoesTblFieldExist(strTable, strField) = False) Then
CurrentDb.Execute "ALTER TABLE " & strTable & " ADD COLUMN " & strField & " " & strType
End If
CreateField = strField
End Function
When i run the query, Access gives me the error "incorrect syntax" (translated) and the cursor stops at the second parenthesis.
Have anyone succeeded with creating fields at runtime on a Access query?
I know i could do this entirely on VBA, but that is not my goal.
Any hints?
That approach attempts to have the db engine determine the name of the destination field when the statement is executed. Unfortunately, Access' db engine does not provide that capability.
Essentially, the statement treats that CreateField() function as a parameter. And Access won't let you use a parameter for a field name.
Consider a straightforward parameter example. This statement succeeds ...
INSERT INTO tblFoo(some_text) VALUES ("bar");
But when providing the same field name (some_text) as a parameter, the statement fails ...
PARAMETERS which_field Text ( 255 );
INSERT INTO tblFoo(which_field) VALUES ("bar");
So you'll need to use 2 operations instead of a single query. You could execute the ALTER TABLE and then a revised INSERT with the field name hard-coded into the statement.

How to include double quotes in select statement?

i have a table like
id name
10 bob
20 bill
i want to select only name column in output with double quotes
like select '"'||name||'"' from table
it is giving me the correct output but is there any other way without using concatenation ...
Thank you..
Using this you can get result with double quotes
' " ' + columnName + ' " '
Example
Query
SELECT '"'+Name+'"' , Age
FROM customer
Result
"Viranja" | 27
Create a virtual column that adds the quotes:
CREATE TABLE
....
quoted_name VARCHAR2 GENERATED ALWAYS AS ('"' || name || '"') VIRTUAL,
...
See here for more information:
http://www.oracle-base.com/articles/11g/virtual-columns-11gr1.php
this will check for any name with at least one double quote
select * from table
where name like '%"%'
If your intention is to be able to "export" the result into space or comma-delimited text file, use a view to "format" your data. You will need to this for your date columns as well.
There are two scenarios you would want to use double quotes in sql in my opinion.
Updating a string column which contains single multiple quotes in it. (you have to escape it)
updating blog contents in columns which you cant edit in "edit top 200 rows"
so, if you want to use double quotes follow this.
SET QUOTED_IDENTIFIER OFF
BEGIN
DECLARE #YourSqlStmt AS VarChar(5000) -- Declare a variable.
SET #YourSqlStmt = "ok"
PRINT #YourSqlStmt -- do your operations here
END
This saves time and you need not to escape single quotes in a existing string content of the column.

Add column in sql server 2005

I am using SQL Server 2005 and JSP. I want to add column having name as string object value.
String dr="Doctor1";
stat1=conn.createStatement();
stat1.executeUpdate("ALTER TABLE dbo.PHPL ADD '"+dr+"' NVARCHAR(255) Null");
It is giving error near column name.I think I am mistaking with syntax. Please help.
String dr="Doctor1";
stat1=conn.createStatement();
stat1.executeUpdate("ALTER TABLE dbo.PHPL ADD "+dr+" NVARCHAR(255) Null");
that works fine.
A couple of issues here
You need to use execute, not executeUpdate. Altering a table is a DDL command, not insert, update or delete
As KittenLS has pointed out, the syntax for ALTER TABLE doesn't need quotes. However, you should use '[]' around to escape spaces, keywords, etc.
i.e.
stat1.execute("ALTER TABLE dbo.PHPL ADD [" + dr + "] NVARCHAR(255) Null");