pythonsqlmysqlpymysql

How to create an sql table in pymysql correctly?


import pymysql.cursors

from config import host, user, password, db_name

try:
    connection = pymysql.connect(
        host=host,
        port=3306,
        user=user,
        password=password,
        database=db_name,
        cursorclass=pymysql.cursors.DictCursor
    )
    try:

        with connection.cursor() as cursor:
            create_table_query = "CREATE TABLE 'user'(id int AUTO_INCREMENT, name varchar(32), password varchar(32), PRIMARY KEY(id);)"
            cursor.execute(create_table_query)
            print("Create")
    finally:
        connection.close()
    print("Success//")
except Exception as ex:
    print("Connecting//")
    print(ex)

Please help! Terminal: Connecting// (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 ''user'(id int AUTO_INCREMENT, name varchar(32), password varchar(32), PRIMARY KE' at line 1")

Process finished with exit code 0

Process finished with exit code 0 Error:(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 ''user'(id int AUTO_INCREMENT, name varchar(32), password varchar(32), PRIMARY KE' at line 1")


Solution

  • If we check your SQL query separatly, it will be as this:

    CREATE TABLE 'user'
    (
       id int AUTO_INCREMENT, 
       name varchar(32), 
       password varchar(32), 
       PRIMARY KEY(id);
    )
    

    As you can see, you have semicolon inside the structure of the table instead of end of the whole operator. Please, try this variant:

    CREATE TABLE 'user'(id int AUTO_INCREMENT, name varchar(32), password varchar(32), PRIMARY KEY(id));
    

    Which we can transfer to the better view:

    CREATE TABLE 'user'
    (
       id int AUTO_INCREMENT, 
       name varchar(32), 
       password varchar(32), 
       PRIMARY KEY(id)
    );