Using “->” in a page to exceute $wpdb query gives error

Code is Code and content is content and they should not be mixed together. the editor is not a code editor, the content can and usually will be transformed in a way you don’t expect which might result in your code failing with no obvious reason.

Just don’t do it. Write your own shortcode that does what you need and use it.