Avoid symbolic error in MySql when user selected options transmitted - mysql

I have VB.net website. Somewhere I have used Update Query which has no errors in terms of syntax but suppose If user has selected some symbolic values like below
UPDATE Table SET Column = ''A'-wing' Where ID = '123'
So here in column the value 'A'-wing has quote which result to syntax error in my query. How do I avoid users option related error in query?

You have to escape your quotes by adding a backslash in front of them. Change your query to this:
UPDATE Table SET Column = '\'A\'-wing' Where ID = '123'
For more informations about this, check the official documentation here.

Related

In MySQL, can I get the column type and and check column values in a single SELECT statement?

I'll start this off by saying I know that there are more practical ways to solve this. It's more of an intellectual curiosity than anything else.
I've inherited a MySQL database where some columns are stored as varchar(5) but actually contain the literals "True" or "False". Changing the structure of the data is not an option right now due to other issues. I'm mapping the columns to an ORM (SQLAlchemy), and I want the column to be mapped to a Boolean data type in the supporting codebase using a type adapter. (I've written this adapter already; it's not the problem.)
To help make the mapping process faster, I'm writing a small query to look at the INFORMATION_SCHEMA table and build a line of Python code defining the column using the ORM's syntax. I cannot assume that the data type varchar(5) is a Boolean column - I need to inspect the contents of that column to see if there are values contained in it besides True and False.
Can I write a query that will both get the column type from INFORMATION_SCHEMA and check the actual values stored in that column?
Here is the query I have so far:
SELECT CONCAT(
"Column(""",
col.column_name,
""", ",
(CASE
WHEN col.DATA_TYPE = "int" THEN "Integer"
-- Code in question
WHEN
col.DATA_TYPE = "varchar"
AND col.CHARACTER_MAXIMUM_LENGTH = 5
AND NOT EXISTS(
-- Doesn't seem to work
SELECT DISTINCT col.COLUMN_NAME
FROM col.TABLE_NAME
WHERE col.COLUMN_NAME NOT IN ("True", "False")
)
THEN "BoolStoredAsVarchar"
WHEN col.DATA_TYPE = "varchar" THEN CONCAT("String(", col.CHARACTER_MAXIMUM_LENGTH, ")")
-- Default if it's not a recognized column type
ELSE col.DATA_TYPE
END),
"),"
) AS alchemy
FROM information_schema.columns AS col
WHERE
col.TABLE_SCHEMA = "my_schema"
AND col.TABLE_NAME = "my_table"
ORDER BY col.ORDINAL_POSITION;
Running this code gives me a permissions error: Error Code: 1142. SELECT command denied to user 'user'#'host' for table 'table_name'. Presumably it's trying to use col.TABLE_NAME as a literal instead of interpreting it.
I've also tried creating a simple stored procedure and making table_name into a variable. However, replacing the FROM clause inside the EXISTS with a variable name gives me a syntax error instead.
Again, it's easy enough to run the query myself to see what's in that column. I'd just like to know if this is possible, and if so, how to do it.
You can't do what you're trying to do in a single query.
The reason is that table names (or any other identifier) must be fixed in the query at the time it is parsed, which is before it has read any values from tables. Thus you can't read the name of a table as a string from information_schema and also read from the table with that name in the same query.
You must read the table name from information_schema and then use that result to format a second query.
This isn't a problem specific to MySQL. It's true of any SQL implementation.

Rails - How to reference model's own column value during update statement?

Is it possible to achieve something like this?
Suppose name and plural_name are fields of Animal's table.
Suppose pluralise_animal is a helper function which takes a string and returns its plural literal.
I cannot loop over the animal records for technical reasons.
This is just an example
Animal.update_all("plural_name = ?", pluralise_animal("I WANT THE ANIMAL NAME HERE, the `name` column's value"))
I want something similar to how you can use functions in MySQL while modifying column values. Is this out-of-scope or possible?
UPDATE animals SET plural_name = CONCAT(name, 's') -- just an example to explain what I mean by referencing a column. I'm aware of the problems in this example.
Thanks in advance
I cannot loop over the animal records for technical reasons.
Sorry, this cannot be done with this restriction.
If your pluralizing helper function is implemented in the client, then you have to fetch data values back to the client, pluralize them, and then post them back to the database.
If you want the UPDATE to run against a set of rows without fetching data values back to the client, then you must implement the pluralization logic in an SQL expression, or a stored function or something.
UPDATE statements run in the database engine. They cannot call functions in the client.
Use a ruby script to generate a SQL script that INSERTS the plural values into a temp table
File.open(filename, 'w') do |file|
file.puts "CREATE TEMPORARY TABLE pluralised_animals(id INT, plural varchar(50));"
file.puts "INSERT INTO pluralised_animals(id, plural) VALUES"
Animal.each.do |animal|
file.puts( "( #{animal.id}, #{pluralise_animal(animal.name)}),"
end
end
Note: replace the trailing comma(,) with a semicolon (;)
Then run the generated SQL script in the database to populate the temp table.
Finally run a SQL update statement in the database that joins the temp table to the main table...
UPDATE animals a
INNER JOIN pluralised_animals pa
ON a.id = pa.id
SET a.plural_name = pa.plural;

spring boot get data from mysql table given by url

I want to create simple app to search some data in specific table.
I've got one database and can connect to it.
Also when I hardcoded table name it works great.
But I want to make url like that:
/demo/{table}/{author}
It should work that i give specific table for eg. 'comedy' and next I set name of author for eg. 'smith'.
My booksRepository:
#Query(value = "SELECT * FROM :table WHERE author = :author",
nativeQuery=true)
public List<Book> findByAuthor(#Param("author") String author, #Param("table") String table);
But it didn't work. I've got error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''comedy' WHERE author = 'Smith'' at line 1
It's adding ' to Query. Is there way to delete that? Is it possible or I need to put everything in one table?
Cheers :)
I haven't looked it up, but it seems that the variables in the query SQL can only be used to insert quoted values, not unquoted identifiers like a table name.

updating mysql database email column with id

I'm trying to update a column used for email in my database with the site id for the same row..
I've tried the following:
UPDATE LOCATIONS
SET email ='se".site_id."#myemail.com'
WHERE customer='MyCustomer' AND site_id='5555';
expecting the email column to be se5555 at myemail.com
but that wasn't the case. Should I use CONCAT?
Use concat function of mysql like this:
UPDATE LOCATIONS SET email = concat('se',site_id,'#myemail.com') WHERE
customer='MyCustomer' AND site_id='5555';
You can definitely use concat(). I also like to use replace() for this type of operation:
UPDATE LOCATIONS
SET email = replace('se<site_id>#myemail.com', '<site_id>', site_id)
WHERE customer = 'MyCustomer' AND site_id = '5555';
This is helpful when you have multiple substitutions -- the first argument is a template so it is easier to see what you are doing and to modify.

Unknown column in 'field list' error on MySQL Update query

I keep getting MySQL error #1054, when trying to perform this update query:
UPDATE MASTER_USER_PROFILE, TRAN_USER_BRANCH
SET MASTER_USER_PROFILE.fellow=`y`
WHERE MASTER_USER_PROFILE.USER_ID = TRAN_USER_BRANCH.USER_ID
AND TRAN_USER_BRANCH.BRANCH_ID = 17
It's probably some syntax error, but I've tried using an inner join instead and other alterations, but I keep getting the same message:
Unknown column 'y' in 'field list'
Try using different quotes for "y" as the identifier quote character is the backtick (`). Otherwise MySQL "thinks" that you point to a column named "y".
See also MySQL 8 Documentation
Please use double-/single quotes for values, strings, etc.
Use backticks for column-names only.
Enclose any string to be passed to the MySQL server inside single quotes, e.g.:
$name = "my name"
$query = " INSERT INTO mytable VALUES ( 1 , '$name') "
Note that although the query is enclosed between double quotes, you must enclose any string in single quotes.
You might check your choice of quotes (use double-/ single quotes for values, strings, etc and backticks for column-names).
Since you only want to update the table master_user_profile I'd recommend a nested query:
UPDATE
master_user_profile
SET
master_user_profile.fellow = 'y'
WHERE
master_user_profile.user_id IN (
SELECT tran_user_branch.user_id
FROM tran_user_branch WHERE tran_user_branch.branch_id = 17);
Just sharing my experience on this. I was having this same issue. The insert or update statement is correct. And I also checked the encoding. The column does exist.
Then! I found out that I was referencing the column in my Trigger.
You should also check your trigger see if any script is referencing the column you are having the problem with.
In my case, it was caused by an unseen trailing space at the end of the column name. Just check if you really use "y" or "y " instead.
While working on a .Net app build with EF code first, I got this error message when trying to apply my migration where I had a Sql("UPDATE tableName SET columnName = value"); statement.
Turns out I misspelled the columnName.
If it is hibernate and JPA. check your referred table name and columns might be a mismatch
Just sharing my experience on this. I was having this same issue. My query was like:
select table1.column2 from table1
However, table1 did not have column2 column.
In my case, the Hibernate was looking for columns in a snake case, like create_date, while the columns in the DB were in the camel case, e.g., createDate.
Adding
spring:
jpa:
hibernate:
naming: # must tell spring/jpa/hibernate to use the column names as specified, not snake case
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
to the application.ymlhelped fix the problem.
In my case, I used a custom table alias for the FROM table, but I used the default table alias (MyTable) in the field list instead of the custom table alias (t1). For example, I needed to change this...
mysql> SELECT MyTable.`id` FROM `MyTable` t1;
...to this...
mysql> SELECT t1.`id` FROM `MyTable` t1;
In my case I had misspelled the column name in the table's trigger. Took me a while to connect the error message with the cause of it.
I too got the same error, problem in my case is I included the column name in GROUP BY clause and it caused this error. So removed the column from GROUP BY clause and it worked!!!
I got this error when using GroupBy via LINQ on a MySQL database. The problem was that the anonymous object property that was being used by GroupBy did not match the database column name. Fixed by renaming anonymous property name to match the column name.
.Select(f => new
{
ThisPropertyNameNeedsToMatchYourColumnName = f.SomeName
})
.GroupBy(t => t.ThisPropertyNameNeedsToMatchYourColumnName);
A query like this will also cause the error:
SELECT table1.id FROM table2
Where the table is specified in column select and not included in the from clause.