Creating a table in mysql has error - mysql

I am creating a table in mysql but it throws some error i am not sure on where is the error and what is the error
Error:
Traceback (most recent call last):
File "whois_redo.py", line 298, in <module>
extractData(url,domain)
File "whois_redo.py", line 76, in extractData
cursor.execute(sql)
File "/usr/local/lib/python2.7/dist-packages/MySQL_python-1.2.4b4-py2.7-linux-x86_64.egg/MySQLdb/cursors.py", line 202, in execute
self.errorhandler(self, exc, value)
File "/usr/local/lib/python2.7/dist-packages/MySQL_python-1.2.4b4-py2.7-linux-x86_64.egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\n PARSE_ERROR INT(5) , \n ORGANIZATION varchar(255) DEFAULT' at line 4")
Where is the error and what is the fix?

It seems that mysql doesn't like the INT(5). Try to use SMALLINT.
More info: http://dev.mysql.com/doc/refman/5.7/en/integer-types.html

The DOMAIN column has an ) that is not needed.
The POSTAL_CODE column has a default clause, but no default value.
I'm not sure that you need multiple " to begin and start the query.

I believe you have an extra parenthesis in line 4:
DOMAIN varchar(255) DEFAULT NULL) ,
Remove it and try it again.

Related

Rename phpmyadmin database name using python code

i have a database and i give it name "test" then
i try to change the database name using python code, but when i run the program the result give me an error warning. here is my code :
def changedb_name():
import mysql.connector
mydb = mysql.connector.connect(host = 'localhost', user='root', password ='')
mycursor = mydb.cursor()
mycursor.execute('ALTER DATABASE test RENAME to test1')
changedb_name()
here is the error warning :
Traceback (most recent call last):
File "c:\Users\NBUSER\Documents\ARTOFWAR\PITON\02-piton\aldo\chgdbname.py", line 18, in <module>
viewdb1()
File "c:\Users\NBUSER\Documents\ARTOFWAR\PITON\02-piton\aldo\chgdbname.py", line 15, in viewdb1
mycursor.execute('RENAME DATABASE test to test1')
File "C:\Users\NBUSER\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\cursor.py", line 568, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Users\NBUSER\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\connection.py", line 846, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
ion.py", line 656, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 'DATABASE test to test1' at line 1
PS C:\Users\NBUSER\Documents\ARTOFWAR\PITON\02-piton> & C:/Users/NBUSER/AppData/Local/Programs/Python/Python39/python.exe c:/Users/NBUSER/Documents/ARTOFWAR/PITON/02-piton/aldo/chgdbname.py
Traceback (most recent call last):
File "c:\Users\NBUSER\Documents\ARTOFWAR\PITON\02-piton\aldo\chgdbname.py", line 18, in <module>
viewdb1()
File "c:\Users\NBUSER\Documents\ARTOFWAR\PITON\02-piton\aldo\chgdbname.py", line 15, in viewdb1
mycursor.execute('ALTER DATABASE test RENAME to test1')
File "C:\Users\NBUSER\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\cursor.py", line 568, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Users\NBUSER\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\connection.py", line 846, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\Users\NBUSER\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\connection.py", line 656, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 'RENAME to test1' at line 1
From where did you find the SQL syntax to ALTER DATABASE...RENAME... ? It seems to me your reference is flawed; that isn't any MySQL syntax I'm familiar with. I believe the ability briefly existed for the blink of an eye. A bit of an internet history search confirms that it hasn't been part of MySQL (pdf) syntax in over 10 years (hat tip to #zloctb).
You can't rename a database in pure SQL. The usual workaround is to export to SQL and re-import to the new database.

PythonAnywhere SQLite/SQLAlchemy suddenly getting errors

SQLAlchemy and SQLite errors appearing on PythonAnywhere but it was fine on localhost.
So I just uploaded my Flask site to pythonanywhere, and when I tried to access it it can't access my database, but is getting a bunch of errors instead.
2021-01-30 10:42:05,740: Exception on /m/550 [GET]
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1248, in _execute_context
self.dialect.do_execute(
File "/usr/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 580, in do_execute
cursor.execute(statement, parameters)
sqlite3.OperationalError: near "(": syntax error
**NO MATCH**
I was not getting these exceptions on my local computer. A little googling and it seems like this is because PA uses an older version of SQLite? Which seems a bit stupid to begin with but it also seems like I can't update it?
So I'm wondering if there is some smart solution to this, or if it would perhaps be easier to switch to MySQL? Would there be other problems in doing that instead? Or do I just need to switch out the SQLALCHEMY_DATABASE_URI to fit MySQL instead? My Current one looks like this:
SQLALCHEMY_DATABASE_URI = 'sqlite:////home/movieelo/cinelow/my_server/database/database.db'
SQLALCHEMY_TRACK_MODIFICATIONS = False
All help and guidence will be greatly appreciated!
UPDATE:
I managed to switch to MySQL but am still getting SQL syntax related errors, such as:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in
your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near '(PARTITION BY
movie_category_scores.category_id ORDER BY movie_category_scores.s' at line 2
**NO MATCH**
UPDATE 2
I think that I have now identiefied the single function that is causing the errors, and it looks like this:
def get_top_movies_by_category(category_id):
query = db.session.query(
MovieCategoryScores,
func.rank()\
.over(
order_by=MovieCategoryScores.score.desc(),
partition_by=MovieCategoryScores.category_id,
)\
.label('rank')
).filter(MovieCategoryScores.votes >= 10)
# now filter
query = query.filter(MovieCategoryScores.category_id == category_id)
query = query.order_by(MovieCategoryScores.category_id, 'rank')
movies = query.all()
return movies
Which generates this error:
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1248, in _execute_context
self.dialect.do_execute(
File "/usr/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 580, in do_execute
cursor.execute(statement, parameters)
sqlite3.OperationalError: near "(": syntax error
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/movieelo/cinelow/my_server/database/pers_movie_dbf.py", line 137, in get_top_movies_by_category
movies = query.all()
File "/usr/lib/python3.8/site-packages/sqlalchemy/orm/query.py", line 3186, in all
return list(self)
File "/usr/lib/python3.8/site-packages/sqlalchemy/orm/query.py", line 3342, in __iter__
return self._execute_and_instances(context)
File "/usr/lib/python3.8/site-packages/sqlalchemy/orm/query.py", line 3367, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "/usr/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 988, in execute
return meth(self, multiparams, params)
File "/usr/lib/python3.8/site-packages/sqlalchemy/sql/elements.py", line 287, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/usr/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1101, in _execute_clauseelement
ret = self._execute_context(
File "/usr/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1252, in _execute_context
self._handle_dbapi_exception(
File "/usr/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1473, in _handle_dbapi_exception
util.raise_from_cause(sqlalchemy_exception, exc_info)
File "/usr/lib/python3.8/site-packages/sqlalchemy/util/compat.py", line 398, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/usr/lib/python3.8/site-packages/sqlalchemy/util/compat.py", line 152, in reraise
raise value.with_traceback(tb)
File "/usr/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1248, in _execute_context
self.dialect.do_execute(
File "/usr/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 580, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) near "(": syntax error
[SQL: SELECT movie_category_scores.votes >= ? AS anon_1, movie_category_scores.movie_id AS movie_category_scores_movie_id, movie_category_scores.category_id AS movie_category_scores_category_id, movie_category_scores.score AS movie_category_scores_score, movie_category_scores.votes AS movie_category_scores_votes, rank() OVER (PARTITION BY movie_category_scores.category_id ORDER BY movie_category_scores.score DESC) AS rank
FROM movie_category_scores
WHERE movie_category_scores.votes >= ? AND movie_category_scores.category_id = ? ORDER BY movie_category_scores.category_id, rank]
[parameters: (10, 10, 11)]
(Background on this error at: http://sqlalche.me/e/e3q8)
Giles Thomas (of PythonAnywhere) confirmed that the SQLite version available on PythonAnywhere doesn't support window functions.
Window functions were added to SQLite version 3.25.0. In the future, you can check whether the SQLite version included with your Python installation supports windows functions by running:
import sqlite3
if sqlite3.sqlite_version_info > (3, 25, 0):
print("Window functions are supported!")
else:
print("Window functions are not supported :(")

Data Migration From SQL Server to MySQL

I am getting this Attribute Error : 'No Type' objectives has no attribute 'split' when i tried to migrate sql db to mysql db in mysql workbench
these are the Log details :
Starting...
Connect to source DBMS...
- Connecting to source...
Connecting to Mssql#sa...
Opening ODBC connection to Driver=sa;DATABASE=;UID=sa;PWD=XXXX...
Connected to Mssql# 11.0.2100.60
Traceback (most recent call last):
File "/Applications/MySQLWorkbench.app/Contents/PlugIns/db_mssql_grt.py", line 147, in connect
_connections[connection.__id__]["version"] = getServerVersion(connection)
File "/Applications/MySQLWorkbench.app/Contents/PlugIns/db_mssql_grt.py", line 174, in getServerVersion
ver_parts = [ int(part) for part in ver_string.split('.') ] + 4*[ 0 ]
AttributeError: 'NoneType' object has no attribute 'split'
Traceback (most recent call last):
File "/Applications/MySQLWorkbench.app/Contents/PlugIns/db_mssql_grt.py", line 174, in getServerVersion
ver_parts = [ int(part) for part in ver_string.split('.') ] + 4*[ 0 ]
AttributeError: 'NoneType' object has no attribute 'split'
Traceback (most recent call last):
File "/Applications/MySQLWorkbench.app/Contents/Resources/libraries/workbench/wizard_progress_page_widget.py", line 65, in run
self.func()
File "/Applications/MySQLWorkbench.app/Contents/PlugIns/migration_source_selection.py", line 406, in task_connect
raise e
SystemError: AttributeError("'NoneType' object has no attribute 'split'"): error calling Python module function DbMssqlRE.getServerVersion
*** ERROR: Error during Connect to source DBMS: AttributeError("'NoneType' object has no attribute 'split'"): error calling Python module function DbMssqlRE.getServerVersion
Traceback (most recent call last):
File "/Applications/MySQLWorkbench.app/Contents/Resources/libraries/workbench/wizard_progress_page_widget.py", line 543, in update_status
task.run()
File "/Applications/MySQLWorkbench.app/Contents/Resources/libraries/workbench/wizard_progress_page_widget.py", line 80, in run
raise e
SystemError: AttributeError("'NoneType' object has no attribute 'split'"): error calling Python module function DbMssqlRE.getServerVersion
*** ERROR: Exception in task 'Connect to source DBMS': SystemError('AttributeError("\'NoneType\' object has no attribute \'split\'"): error calling Python module function DbMssqlRE.getServerVersion',)
Failed
i tried a solution (given below , taken from the link https://bugs.mysql.com/bug.php?id=66030&thanks=3&notify=195). but it didn't help. I still get the same error. Please help me.
solution:
// We'll need some help from you to diagnose this one. With a text editor, open the /Applications/MySQLWorkbench.app/Contents/PlugIns/db_mssql_grt.py file
and around line 174 you'll find a line that looks like:
ver_string = execute_query(connection, "SELECT SERVERPROPERTY('ProductVersion')").fetchone()[0]
Change that to:
ver_string = execute_query(connection, "SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR)").fetchone()[0]
Then save and retry. Thanks! //

Pycharm: MySQLdb and database

the code in Pycharm :
import MySQLdb
db = MySQLdb.connect("127.0.0.1", "xxx", "xxx", "xxxxxxx")
cursor = db.cursor()
sql="""CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INI,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
db.close()
the problem :
/usr/bin/python2.7 /home/mfae/PycharmProjects/dbs/create.py
/usr/lib/python2.7/dist-packages/pkg_resources.py:1031: UserWarning: /home/mfae/.python-eggs is writable by group/others and vulnerable to attack when used with get_resource_filename. Consider a more secure location (set with .set_extraction_path or the PYTHON_EGG_CACHE environment variable).
warnings.warn(msg, UserWarning)
Traceback (most recent call last):
File "/home/mfae/PycharmProjects/dbs/create.py", line 14, in <module>
cursor.execute(sql)
File "build/bdist.linux-i686/egg/MySQLdb/cursors.py", line 205, in execute
File "build/bdist.linux-i686/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INI,\n SEX CHAR(1),\n INCOME FLOAT )' at line 4")
Process finished with exit code 1
Process finished with exit code 1
Process finished with exit code 1
Process finished with exit code 1
what the solution ?
Like the error says, you should
change AGE INI to AGE INT.

Sqlalchemy can't connect to a mysql server

My legacy mysql 4.0.20 server is on a windows machine.
I'm developing a new system (python based) on a linux that needs to connect to the legacy server and make queries etc.
I have successfully connected using both plain MySQLdb and django. I'm having trouble connecting using sqlalchemy. Here is the code:
conn_str = "mysql://user:pass#192.168.171.233/dbd"
engine = create_engine(conn_str, echo=True)
metadata = MetaData(engine)
connection = engine.connect()
and the error stack I'm getting:
2011-03-01 08:35:04,613 INFO sqlalchemy.engine.base.Engine.0x...b42c SELECT DATABASE()
2011-03-01 08:35:04,613 INFO sqlalchemy.engine.base.Engine.0x...b42c ()
Traceback (most recent call last):
connection = engine.connect()
File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/engine/base.py", line 1811, in connect
return self.Connection(self, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/engine/base.py", line 832, in init
self.connection = connection or engine.raw_connection()
File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/engine/base.py", line 1874, in raw_connection
return self.pool.unique_connection()
File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/pool.py", line 142, in unique_connection
return _ConnectionFairy(self).checkout()
File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/pool.py", line 369, in __init
rec = self._connection_record = pool.get()
File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/pool.py", line 213, in get
return self.do_get()
File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/pool.py", line 732, in do_get
con = self.create_connection()
File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/pool.py", line 147, in create_connection
return _ConnectionRecord(self)
File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/pool.py", line 258, in init
l.first_connect(self.connection, self)
File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/engine/strategies.py", line 151, in first_connect
dialect.initialize(c)
File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/dialects/mysql/base.py", line 1753, in initialize
default.DefaultDialect.initialize(self, connection)
File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/engine/default.py", line 159, in initialize
self.returns_unicode_strings = self._check_unicode_returns(connection)
File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/engine/default.py", line 205, in _check_unicode_returns
unicode_for_varchar = check_unicode(sqltypes.VARCHAR(60))
File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/engine/default.py", line 195, in check_unicode
]).compile(dialect=self)
File "/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3c1-py2.6-linux-i686.egg/MySQLdb/cursors.py", line 173, in execute
self.errorhandler(self, exc, value)
File "/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3c1-py2.6-linux-i686.egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
ProgrammingError: (1064, "You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near '(60)) AS anon_1' at line 1")
Looks like MySQL is reporting a syntax error in one of your SQL statements:
<snip>
1064, "You have an error in your SQL syntax.
Check the manual that corresponds to your MySQL server
version for the right syntax to use near
'(60)) AS anon_1' at line 1
</snip>
It looks like MySQL is objecting to a statement that includes the string:
(60)) AS anon_1
NOTE: I am not familiar with Sqlalchemy, but it looks to me like the exception (the SQL error from the statement) is getting propagated up to the handler specified in the connection.
FOLLOWUP: It's likely that a query that Sqlalchemy is executing is not compatible with the older version of MySQL. Looks like it's in the "_check_unicode_returns" function.
Have you tried disabling unicode support?
conn_str = "mysql://user:pass#192.168.171.233/dbd?use_unicode=0"