from sqlalchemy.dialects.mysql import INTEGER,VARCHAR
from sqlalchemy import Column
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
Base=declarative_base()
# Users表结构
class Users(Base):
__tablename__='users'
id = Column(INTEGER , primary_key = True)
name = Column(VARCHAR(256) , nullable = False)
age = Column(INTEGER)
place = Column (VARCHAR(256),nullable = False)
def __init__(self , id , name , age , place):
self.id = id
self.name = name
self.age = age
self.place = place
def init_db():
engine = create_engine(
"mysql+pymysql ://root :123456 @localhost/hjwzd",
encoding = "utf-8",
echo = True,
autocommit=True #设置自动提交
)
Base.metadata.create_all(engine)
print('Create table successfully!')
#建立数据库连接
if __name__=='__main__':
init_db()
PS C:\Users\86181\Desktop\violeter> & c:/Users/86181/Desktop/violeter/.venv/Scripts/python.exe "c:/Users/86181/Desktop/violeter/Face recognition/create_table.py"
c:\Users\86181\Desktop\violeter\Face recognition\create_table.py:10: MovedIn20Warning: The ``declarative_base()`` function is now available as sqlalchemy.orm.declarative_base(). (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9)
Base=declarative_base()
Traceback (most recent call last):
File "c:\Users\86181\Desktop\violeter\Face recognition\create_table.py", line 40, in <module>
init_db()
File "c:\Users\86181\Desktop\violeter\Face recognition\create_table.py", line 28, in init_db
engine = create_engine(
^^^^^^^^^^^^^^
File "<string>", line 2, in create_engine
File "C:\Users\86181\Desktop\violeter\.venv\Lib\site-packages\sqlalchemy\util\deprecations.py", line 281, in warned
return fn(*args, **kwargs) # type: ignore[no-any-return]
^^^^^^^^^^^^^^^^^^^
File "C:\Users\86181\Desktop\violeter\.venv\Lib\site-packages\sqlalchemy\engine\create.py", line 546, in create_engine
u = _url.make_url(url)
^^^^^^^^^^^^^^^^^^
File "C:\Users\86181\Desktop\violeter\.venv\Lib\site-packages\sqlalchemy\engine\url.py", line 842, in make_url
return _parse_url(name_or_url)
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\86181\Desktop\violeter\.venv\Lib\site-packages\sqlalchemy\engine\url.py", line 908, in _parse_url
raise exc.ArgumentError(
sqlalchemy.exc.ArgumentError: Could not parse SQLAlchemy URL from string 'mysql+pymysql ://root :123456 @localhost/hjwzd'
PS C:\Users\86181\Desktop\violeter>
create_engine的参数不能加空格