MySQL初识2

用python调用mysql的一些方法总结:

1.编码声明:

# encoding: UTF-8
#!/usr/bin/python

在开头处进行声明,避免出现输入中文时,提示声明错误(当然输入中文出现乱码情况,需要另外解决)

2.调用时要注意,host =‘localhost’,此处需注意,有时候用自己服务器‘120.24.85.37’,但是会出现_mysql_operation_error(2013...)之类的错误,可尝试用‘localhost’/’127.0.0.0‘进行解决;但是何种情况下用localhost,何种情况用自己服务器,需要再后期再更清晰的弄明白。

3.python调用mysql需要MySQLdb包,安装方法按照其它第三方包安装即可

4.python调用mysql常用操作命令:

import  MySQLdb

conn = MySQLdb.connect(

host = 'lacalhost',

port =22,此处为端口位置,数据类型为整型,不需要加引号

user=’‘,

passwd= '',此处为数据库的用户名和密码

db = '')

cur = conn.cursor()

cur.execute("create table student(id int,name char(30),class char(50))") ==>创建数据表

cur.execute("insert into student values("2","tom","3year 2class")")==>插入一条数值

插入优化:

sql = "insert into student values(%s,%s,%s)"

插入1条数据:cur.execute(sql,(“2”,“tom”,"3year 2class"))

插入多条数据:cur.executemany(sql,[("2","tom","3year2class"),

("3","lily","3year2class")])

cur.execute("update student set class = '3year 1class' where name = 'tom'")==>根据条件修改数据

cur.execute("delete from student where class = '3year 2class'") ==>删除符合条件的数据

sql= "select * from student"

cur.execute(sql)

info = cur.fetchall()==>获取表中的所有信息

for row in info:

  print row

==>打印出表中的所有元素

cur.close() ==>关闭游标

conn.commit()==>提交事务,向数据库插入时不可缺少

conn.close() ==>关闭连接

原文地址:https://www.cnblogs.com/wangzhao2016/p/5513834.html