python中数据库操作

使用MysqlDb操作数据库时具体操作如下:


1.插入操作

    id = '1'
    name = 'sara'
    content = 'hello'

    sql = "insert into table_name (id, name, content) values (%d, %s, %s);"
    param = (id, name, content)
    r = cursor.execute(sql, param)
    conn.commit()

2.更新操作

psd = 'test111111111'
field_name1 = 'test'
id = 1
ip = '192.168.1.1'

sql = "update table_name set password = '" + psd + "', field_name1 = '" + field_name1 + "', field_name2 = 1 where id = '" + id + "' and ip = INET_ATON('" + ipaddr + "');"
cursor.execute(sql)
conn.commit()

3.查询操作

id = 1

sql = "select inet_ntoa(ipaddr), id from table_name where id = " + "'" + id + "';"
cursor.execute(sql)
info = cursor.fetchone()

注意:

(1)ip地址一般在数据库中使用int(10) unsiged类型存储,存取时要注意类型转换。
(2)插入或更新操作时,如果插入的数据是存储在变量中的,注意sql语句的书写方式。

你可能感兴趣的:(python中数据库操作)