Python中MySQLdb模块的使用
python下连接数据库存取数据比c++方便多了,真是越来越爱python了。
首先安装MySQLdb模块,直接官网下载exe文件,双击安装即可。
#导入模块
import MySQLdb;
#连接数据库,返回已连接的对象
conn = MySQLdb.connect(host="localhost",user="root",passwd="791745",db="username");
#创建游标
cur = conn.cursor();
#选择数据库
conn.select_db('tpms');
#添加数据
cur.execute("insert into username(UserName,PassWords) value('zhu','789654')");
#添加多条数据
sqil = "insert into username(UserName,PassWords) value('zhu','789654')";
cur.executemany(sqil,[('hjk','456'),('jkljk','789')]);
#删除数据
cur.execute("delete from username where UserName = 'cvst'");
#更新数据
cur.execute("update username set PassWords = '789456' where UserName = 'jkljk'");
#之前的操作完后,虽然返回了正确的结果,但是数据库中的数并没有改变,因此需要提交至数据库:
conn.commit();
#获取搜索结果中的第n条,按指针递增
cur.fetchone();
#将结果指针返回到第一条
cur.scroll(0,'absolute');
#一次性获取多条结果放在元组中
cur.fetchmany(11);
#关闭游标
cur.close();
#关闭连接
conn.close();