skip to Main Content

I’m new in Python and trying to learn MySQL

as we import pymysql

import pymysql
from datetime import datetime

conn = pymysql.connect(
    host = 'localhost',
    user = 'root',
    password = '',
    database = 'test'
)
mycursor = conn.cursor()
sql = "INSERT INTO led (id,name,date) VALUES (%i,%s,%d,)"

my question is if we have the values of datatypes id = %i, name =%s and date = %d , what are the %? of datetime, time and timestamp..?

I got errors on inserting data while i don not know that exact %? of the all datatypes. if some one has link to learn these datatypes values %? please share the link or if you get my question please answer… I am inserting data i use functions but got NoModuleError. now(), current_date(),datetime()

please let me know that what are the %? of datetime, time and timestamp..?

2

Answers


  1. I assume ‘%s’ since a properly formatted DATE literal is indisposable from ‘2024-01-25’. (Etc.) If you need, for example, the year last, you will have to convert it before or after feeding it to MySQL.

    Login or Signup to reply.
  2. If you are using the format ("%s") paramstyle for value placeholders in queries, the placeholder is always "%s", regardless of the type of the value being substituted.

    cursor.execute(
        """INSERT INTO t (a, b, c) VALUES (%s, %s, %s)""",
        (1, 'a', datetime.date(2024, 1, 26))
    )
    

    Type-specific placeholders like "%d" or "%i" are used in printf-style string formatting, (spam = 'I am %d years old' % 42). This looks similar to value placeholders in queries, but it is not the same. This technique (and similar like f-strings and str.format) should not be used to construct SQL queries because it does not provide any defence against SQL injection.

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