skip to Main Content

I’ve installed MySQL on my Windows desktop. The installation was successful. I downloaded the employees data from github and added it to my MySql server. I confirmed that through the MySQL 8.4 Command Line Client

I’m working through the Documentation for the MySQL Connector/Python Developer Guide. I got to inserting data into the employee database. I get this error: DatabaseError: 1364 (HY000): Field 'emp_no' doesn't have a default value

The answers to this question are about PHP, not python: mysql error 1364 Field doesn't have a default values

This question is about default values for Datetime: How do you set a default value for a MySQL Datetime column?

Except for the **config, this code is a cut-n-paste from the dev.mysql.com hyperlink. And except for the 'password': '****', here’s the code that I used:

from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector

config = {
    'user': 'root',
    'password': '****',
    'host': '127.0.0.1',
    'database': 'employees'
}

cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()

tomorrow = datetime.now().date() + timedelta(days=1)

add_employee = ("INSERT INTO employees "
               "(first_name, last_name, hire_date, gender, birth_date) "
               "VALUES (%s, %s, %s, %s, %s)")
add_salary = ("INSERT INTO salaries "
              "(emp_no, salary, from_date, to_date) "
              "VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")

data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))

# # Insert new employee
# cursor.execute(add_employee, data_employee)
# emp_no = cursor.lastrowid

# # Insert salary information
# data_salary = {
#   'emp_no': emp_no,
#   'salary': 50000,
#   'from_date': tomorrow,
#   'to_date': date(9999, 1, 1),
# }
# cursor.execute(add_salary, data_salary)

# # Make sure data is committed to the database
# cnx.commit()

cursor.close()
cnx.close()

Now, I know it connects because if I comment out the two Insert blocks, it runs fine. But here is the error message when it runs as posted in this question.

Traceback (most recent call last):
  File "C:UsersUserDocumentsPythonTutorials.venvLibsite-packagesmysqlconnectorconnection_cext.py", line 697, in cmd_query
    self._cmysql.query(
_mysql_connector.MySQLInterfaceError: Field 'emp_no' doesn't have a default value

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "c:UsersUserDocumentsPythonTutorialsAdd_to_Employees.py", line 27, in <module>
    cursor.execute(add_employee, data_employee)
  File "C:UsersUserDocumentsPythonTutorials.venvLibsite-packagesmysqlconnectorcursor_cext.py", line 372, in execute
    result = self._cnx.cmd_query(
             ^^^^^^^^^^^^^^^^^^^^
  File "C:UsersUserDocumentsPythonTutorials.venvLibsite-packagesmysqlconnectoropentelemetrycontext_propagation.py", line 102, in wrapper
    return method(cnx, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:UsersUserDocumentsPythonTutorials.venvLibsite-packagesmysqlconnectorconnection_cext.py", line 705, in cmd_query
    raise get_mysql_exception(
mysql.connector.errors.DatabaseError: 1364 (HY000): Field 'emp_no' doesn't have a default value

DISCLAIMER: I know not to put my password in the file. I trying to solve one problem at a time.

EDIT:
When I ALTER TABLE employees MODIFY emp_no INT NOT NULL AUTO_INCREMENT; in MySQL 8.4 Command Line Client,I get this error:

ERROR 1833 (HY000): Cannot change column 'emp_no': used in a foreign key constraint 'dept_manager_ibfk_1' of table 'employees.dept_manager'

Here’s the TABLE DEFINITON
enter image description here

enter image description here

2

Answers


  1. I think the problem starts with the MySQL database employees table. This table doesn’t have a default value or auto-increment for emp_no. Therefore, you have to add emp_no manually while inserting data, like below:

    add_employee = ("INSERT INTO employees "
                   "(emp_no, first_name, last_name, hire_date, gender, birth_date) "
                   "VALUES (%s, %s, %s, %s, %s, %s)")
    

    Alternatively, you can change your table to have emp_no as an auto-increment field:

    ALTER TABLE employees MODIFY emp_no INT NOT NULL AUTO_INCREMENT;
    

    Or, drop the table and recreate it with emp_no set to auto-increment:

    DROP TABLE employees;
    
    CREATE TABLE employees (
        emp_no INT NOT NULL AUTO_INCREMENT,
        first_name VARCHAR(50),
        last_name VARCHAR(50),
        hire_date DATE,
        gender ENUM('M', 'F'),
        birth_date DATE,
        PRIMARY KEY (emp_no)
    );
    
    Login or Signup to reply.
  2. ERROR 1833 (HY000): Cannot change column 'emp_no': used in a foreign key constraint 'dept_manager_ibfk_1' of table 'employees.dept_manager'
    

    You are getting this error because emp_no is already a foreign key in the following tables:

    • dept_emp
    • salaries
    • dept_manager
    • titles

    You need to temporarily drop these foreign key constraints, modify the column, and then re-add the constraints.

    1. Drop foreignt key constraints.

       ALTER TABLE dept_emp DROP FOREIGN KEY dept_emp;
      
       ALTER TABLE dept_manager DROP FOREIGN KEY dept_manager;
      
       ALTER TABLE salaries DROP FOREIGN KEY salaries;
      
       ALTER TABLE titles DROP FOREIGN KEY titles;
      
    2. Modify the emp_no column.

       ALTER TABLE employees MODIFY emp_no INT NOT NULL AUTO_INCREMENT;
      
    3. Re-add the dropped foreign keys to tables.

       ALTER TABLE dept_emp ADD CONSTRAINT dept_emp FOREIGN KEY (emp_no) REFERENCES employees(emp_no);
      
       ALTER TABLE dept_manager ADD CONSTRAINT dept_manager FOREIGN KEY (emp_no) REFERENCES employees(emp_no);
      
       ALTER TABLE salaries ADD CONSTRAINT salaries FOREIGN KEY (emp_no) REFERENCES employees(emp_no);
      
       ALTER TABLE titles ADD CONSTRAINT titles FOREIGN KEY (emp_no) REFERENCES employees(emp_no);
      

    maybe will help:
    https://kedar.nitty-witty.com/blog/mysql-change-datatype-column-foreign-key-constraint

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search