Home > Database > Mysql Tutorial > How to Correctly Insert Integer Data into a MySQL Database Using Python?

How to Correctly Insert Integer Data into a MySQL Database Using Python?

Mary-Kate Olsen
Release: 2024-11-30 14:24:11
Original
503 people have browsed it

How to Correctly Insert Integer Data into a MySQL Database Using Python?

Inserting Data into MySQL Database

You want to insert data into your MySQL database using integers. However, the code you provided is encountering an issue.

Issue:

The code:

import MySQLdb
conn = MySQLdb.connect(host= "localhost",
                  user="root",
                  passwd="newpassword",
                  db="engy1")
x = conn.cursor()
x.execute("SELECT *  FROM anooog1")
x.execute (" INSERT INTO anooog1 VALUES ('%s','%s') ", (188,90))
row = x.fetchall()
Copy after login

fails to insert data into your database because of the following error:

Solution:

To resolve this issue, the code should be modified as follows:

import MySQLdb

# Connect to the database
conn = MySQLdb.connect(host="localhost", user="root", passwd="newpassword", db="engy1")
x = conn.cursor()

# Insert data into the database
try:
    x.execute("INSERT INTO anooog1 VALUES (%s,%s)", (188, 90))
    conn.commit()
except:
    conn.rollback()

# Close the connection
conn.close()
Copy after login

Explanation:

The updated code includes the following changes:

  • The formatting of the INSERT statement using string substitution ('%s', '%s') is removed.
  • Instead, the tuple (188, 90) is直接passed as a parameter to the execute method.
  • The cursor is placed within a try/except block to handle any potential errors during the insertion process.

The above is the detailed content of How to Correctly Insert Integer Data into a MySQL Database Using Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template