Python使用MYSQL

作者: peterzen | 来源:发表于2019-07-03 18:44 被阅读0次

安装

> pip install PyMySQL

不能使用pip install MySQL-Python, 不支持python3, 会报错需要visual studio14.

使用

import pymysql

conn = pymysql.connect(host="localhost", user="root", passwd="pass", db="world" )
cur = conn.cursor()
cur.execute( "DROP TABLE IF EXISTS filelist" )
sql = """CREATE TABLE filelist( handle INT UNIQUE,
  filename TEXT,
  datetime DATETIME,
  duration INT)"""
cur.execute( sql )

cur.execute( "INSERT INTO filelist VALUES( '%d', '%s', '%s', 10 ) % ( 1, "sample.mp4", "2019-07-03 18:04:30" ) )
cur.commit()

cur.execute( "SELECT * from filelist" )
for r in cur:
  print r

cur.close()
conn.close()
  1. connect()中db的参数是要连接的数据库名字;
  2. 要执行sql语句,要先获取到cursor;
  3. 当有多行SQL语句时,用""" """把语句引起来,可以不用换行时yoga转义字符;
  4. 当执行INSERT这类对数据库有改变的语句是,需要commit(),否则不生效;
  5. 当有变量要取值来插入时,格式为"INSERT INTO filelist VALUES( '%d', '%s', '%s', 10 ) % ( 1, "sample.mp4", "2019-07-03 18:04:30" );
  6. 当SQL有DATETIME的数据类型时,可以用string作为input;

Python中DateTime的使用

from datetime import datetime

day = datetime( 2018, 1, 1, 8, 20, 30)
print( str(day))

使用datetime lib中的datetime类;
str(day)得到的string格式为"2019-07-03 18:39:20"

DateTime加减

from datetime import timedelta

time = time + timedelta( minutes=10)

timedelta的参数可以有 days, hours, minutes等,可以很方便的进行时间加减。

相关文章

网友评论

    本文标题:Python使用MYSQL

    本文链接:https://www.haomeiwen.com/subject/mcufhctx.html