Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore pymysql warnings?

Consider this code:

import pymysql

db= pymysql.connect("localhost","root","","raspi")
cursor = db.cursor()
cursor.execute("INSERT INTO access(username)VALUES('hello')")
db.commit()
db.close()

when I run it I'll get this error:

C:\Python36\lib\site-packages\pymysql\cursors.py:165: Warning: (1364,"Field'salt' doesn't have a default value")result = self._query(query)

How do I ignore pymysql warnings?

like image 258
ArchDevOps Avatar asked Jun 30 '18 09:06

ArchDevOps


People also ask

What is PyMySQL cursor?

class pymysql.cursors. Cursor (connection) This is the object used to interact with the database. Do not create an instance of a Cursor yourself. Call connections.

What does PyMySQL fetchAll return?

PyMySQL fetchAll The fetchall function gets all records. It returns a result set. Technically, it is a tuple of tuples. Each of the inner tuples represent a row in the table.

What is the difference between PyMySQL and MySQL?

PyMySQL and MySQLdb provide the same functionality - they are both database connectors. The difference is in the implementation where MySQLdb is a C extension and PyMySQL is pure Python. There are a few reasons to try PyMySQL: it might be easier to get running on some systems.

What is PyMySQL connect?

PyMySQL is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2. 0 and contains a pure-Python MySQL client library. The goal of PyMySQL is to be a drop-in replacement for MySQLdb.


1 Answers

Reason why you're getting that error is because your salt field is not allowing NULL values but you're trying to insert them, probably your table creation sql code looks something like this:

CREATE TABLE `access` (
    `username` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
    ...
    `salt` VARCHAR(50) NOT NULL COLLATE 'utf8_unicode_ci'
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB
;

If you just wanted to allow NULL values for that field maybe your SQL code would need to be change into something like:

...
`salt` VARCHAR(50) NULL COLLATE 'utf8_unicode_ci'
...

Anyway, if you still insist to keep your original db structure and want to learn how filter out warnings, here's a possible way to you could do it:

import pymysql
import warnings


db = pymysql.connect("localhost", "root", "", "raspi")

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    cursor = db.cursor()
    cursor.execute("INSERT INTO access(username)VALUES('hello')")
    db.commit()
    db.close()

For more information, take a look to the warnings docs

like image 91
BPL Avatar answered Oct 15 '22 22:10

BPL