MySQL与Python交互,,一、安装mysql二


一、安装mysql

二、安装第三方模块(python2.7下)

三、新建数据库

四、数据库的增、删、改、查

五、封装

1.1 首先安装mysql

sudo apt-get install mysql-server mysql-client

1.2 mysql的启动、停止、重启

service mysql startservice mysql stopservice mysql restart

1.3 允许远程连接

1.找到mysql配置文件并修改sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf# bind-address=127.0.0.12.登录mysql,运行命令 grant all privileges on *.* to ‘root‘@‘%‘ identified by ‘mysql‘ with grant option;flush privileges;
3.重启 mysql

2.1 安装mysql模块

sudo pip install MySQL-python
pip install pymysql(python3)

2.2建立与数据库的连接

1.创建对象:调用connect()方法conn=connect(参数列表)
参数host:连接的mysql主机,如果本机是‘localhost‘参数port:连接的mysql主机的端口,默认是3306参数db:数据库的名称参数user:连接的用户名参数password:连接的密码参数charset:通信采用的编码方式,默认是‘gb2312‘,要求与数据库创建时指定的编码一致,否则中文会乱码

2.3 对象的方法

close()关闭连接commit()事务,所以需要提交才会生效rollback()事务,放弃之前的操作cursor()返回Cursor对象,用于执行sql语句并获得结果

  执行sql语句

  创建对象:调用Connection对象的cursor()方法  cursor1=conn.cursor()
close()关闭execute(operation [, parameters ])执行语句,返回受影响的行数fetchone()执行查询语句时,获取查询结果集的第一个行数据,返回一个元组next()执行查询语句时,获取当前行的下一行fetchall()执行查询时,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回scroll(value[,mode])将行指针移动到某个位置mode表示移动的方式mode的默认值为relative,表示基于当前行移动到value,value为正则向下移动,value为负则向上移动mode的值为absolute,表示基于第一条数据的位置,第一条数据的位置为0

2.4对象的属性

rowcount只读属性,表示最近一次execute()执行后受影响的行数connection获得当前连接对象

3.1 在student数据库中新建users表

使用sha1加密

create table users(    id int primary key auto_increment,    uname varchar(20),    upwd char(40),    isdelete bit default 0);

3.2 加入测试数据

INSERT INTO users(`id`, `uname`, `upwd`, `isdelete`) VALUES (1, ‘user1‘, ‘40bd001563085fc35165329ea1ff5c5ecbdbbeef‘, b‘0‘);INSERT INTO users(`id`, `uname`, `upwd`, `isdelete`) VALUES (2, ‘user2‘, ‘51eac6b471a284d3341d8c0c63d0f1a286262a18‘, b‘0‘);

4.1 增加、修改、删除

 1  # encoding=utf-8 2  import MySQLdb 3   4  try: 5      conn = MySQLdb.connect(host=‘localhost‘, port=3306, db=‘student‘, user=‘root‘, passwd=‘root‘, charset=‘utf8‘) 6      cur = conn.cursor() 7  # 增加 8    sql1 = "insert into users(id,uname) values(3,‘张三‘)" 9  # 修改10  # sql = "update users set uname=‘李四‘ where id=4"11  # 删除12  # sql = "delete from users where id=5"13      count = cur.execute(sql)14      conn.commit()15      cs1.close()16      conn.close()17  except Exception as e:18     print e.message

4.2 查询

1. 查询一行数据#encoding=utf8import MySQLdbtry:  conn=MySQLdb.connect(host=‘localhost‘,port=3306,db=‘student‘,user=‘root‘,passwd=‘mysql‘,charset=‘utf8‘)    cur=conn.cursor()    cur.execute(‘select * from users where id=1‘)    result=cur.fetchone()    print result    cur.close()    conn.close()except Exception,e:    print e.message2. 查询多行数据#encoding=utf8import MySQLdbtry:    conn=MySQLdb.connect(host=‘localhost‘,port=3306,db=‘student‘,user=‘root‘,passwd=‘mysql‘,charset=‘utf8‘)    cur=conn.cursor()    cur.execute(‘select * from users‘)    result=cur.fetchall()    print result    cur.close()    conn.close()except Exception,e:    print e.message

5.1 封装

技术分享图片
# encoding=utf8import MySQLdbimport hashlibclass MysqlHelper():    def __init__(self, host, port, db, user, passwd, charset=‘utf8‘):        self.host = host        self.port = port        self.db = db        self.user = user        self.passwd = passwd        self.charset = charset    def connect(self):        # 创建对象:调用connect()方法        self.conn = MySQLdb.connect(host=self.host, port=self.port, db=self.db, user=self.user, passwd=self.passwd,                                    charset=self.charset)        self.cursor = self.conn.cursor()    def close(self):        self.cursor.close()        self.conn.close()    # fetchone() :    # 返回单个的元组,也就是一条记录(row),如果没有结果    # 则返回    # None    # fetchall() :    # 返回多个元组,即返回多个记录(rows), 如果没有结果    # 则返回()    # 需要注明:在MySQL中是NULL,而在Python中则是None    def get_one(self, sql, params=()):        result = None        try:            self.connect()            self.cursor.execute(sql, params)            result = self.cursor.fetchone()            self.close()        except Exception, e:            print e.message        return result    def get_all(self, sql, params=()):        list = ()        try:            self.connect()            self.cursor.execute(sql, params)            list = self.cursor.fetchall()            self.close()        except Exception, e:            print e.message        return list    def insert(self, sql, params=()):        return self.__edit(sql, params)    def update(self, sql, params=()):        return self.__edit(sql, params)    def delete(self, sql, params=()):        return self.__edit(sql, params)    def __edit(self, sql, params):        count = 0        try:            self.connect()            # 创建对象:调用Connection对象的cursor() 方法            # 执行语句,返回受影响的行数: execute(operation[, parameters])            count = self.cursor.execute(sql, params)            self.conn.commit()            self.close()        except Exception as e:            print e        return count
mysql封装类技术分享图片
# encoding=utf-8from MysqlHelper import MysqlHelperfrom hashlib import sha1def main():    sqlhelper = MysqlHelper(‘127.0.0.1‘, 3306, ‘student‘, ‘root‘, ‘root‘)    # 用户登录    sname = raw_input("请输入用户名:")    spwd = raw_input("请输入密码:")    # - update(arg):根据参数来更新hash对象,    # 多个update调用相当于把所有参数连接起来的单个update调用    # - digest():返回hash字符串    # - hexdigest():返回hash字符串,16进制    # - copy():返回一个clone对象    s1 = sha1()    s1.update(spwd)    spwdSha1 = s1.hexdigest()    sql = "select upwd from users where uname=%s"    params = [sname]    userinfo = sqlhelper.get_one(sql, params)    if userinfo == None:        print ‘用户名错误‘    elif userinfo[0] == spwdSha1:        print ‘登录成功‘    else:        print ‘密码错误‘if __name__ == ‘__main__‘:    main()
登录

MySQL与Python交互

评论关闭