浅谈MySQL在cmd和python下的常用操作
环境配置1:安装mysql,环境变量添加mysql的bin目录
环境配置2:python安装MySQL-Python
请根据自身操作系统下载安装,否则会报c++compile9.0,import_mysql等错误
windows1064位操作系统可到http://www.lfd.uci.edu/~gohlke/pythonlibs/下载安装MySQL-Python包,至于whl和tar.gz在windows和Linux下的安装方法可查看我的上一篇文章
一、cmd命令下的操作:
连接mysql:mysql-uroot-p
查看所有数据库:showdatabases;
创建test数据库:createdatabasetest;
删除数据库:dropdatabasetest;
使用(切换至)test数据库:usetest;
查看当前数据库下的表:showtables;
创建UserInfo表:createtableUserInfo(idint(5)NOTNULLauto_increment,usernamevarchar(10),passwordvarchar(20)NOTNULL,PRIMARYKEY(id));
删除表:droptableUserInfo;
判断数据是否存在:select*fromUserInfowherenamelike'elijahxb';
增数据:insertintoUserInfo(username,password)value('eljiahxb','123456');
查数据:select*fromUserInfo;selectidfromUserInfo;selectusernamefromUserInfo;
改数据:updateUserInfosetusername='Zus'whereid=1;updateUserInfosetusername='Zus';
删数据:deletefromUserInfo;deletefromUserInfowhereid=1;
断开连接:quit
二、python下的操作:
#-*-coding:utf-8-*-
#!/usr/bin/envpython
#@Time:2017/6/418:11
#@Author:Elijah
#@Site:
#@File:sql_helper.py
#@Software:PyCharmCommunityEdition
importMySQLdb
classMySqlHelper(object):
def__init__(self,**args):
self.ip=args.get("IP")
self.user=args.get("User")
self.password=args.get("Password")
self.tablename=args.get("Table")
self.port=3306
self.conn=self.conn=MySQLdb.Connect(host=self.ip,user=self.user,passwd=self.password,port=self.port,connect_timeout=5,autocommit=True)
self.cursor=self.conn.cursor()
defClose(self):
self.cursor.close()
self.conn.close()
defexecute(self,sqlcmd):
returnself.cursor.execute(sqlcmd)
defSetDatabase(self,database):
returnself.cursor.execute("use%s;"%database)
defGetDatabasesCount(self):
returnself.cursor.execute("showdatabases;")
defGetTablesCount(self):
returnself.cursor.execute("showtables;")
defGetFetchone(self,table=None):
ifnottable:
table=self.tablename
self.cursor.execute("select*from%s;"%table)
returnself.cursor.fetchone()
defGetFetchmany(self,table=None,size=0):
ifnottable:
table=self.tablename
count=self.cursor.execute("select*from%s;"%table)
returnself.cursor.fetchmany(size)
defGetFetchall(self,table=None):
'''
:paramtable:列表
:return:
'''
ifnottable:
table=self.tablename
self.cursor.execute("select*from%s;"%table)
returnself.cursor.fetchall()
defSetInsertdata(self,table=None,keyinfo=None,value=None):
"""
:paramtable:
:paramkeyinfo:可以不传此参数,但此时value每一条数据的字段数必须与数据库中的字段数一致。
传此参数时,则表示只穿指定字段的字段值。
:paramvalue:类型必须为只有一组信息的元组,或者包含多条信息的元组组成的列表
:return:
"""
ifnottable:
table=self.tablename
slist=[]
iftype(value)==tuple:
valuelen=value
execmany=False
else:
valuelen=value[0]
execmany=True
foreachinrange(len(valuelen)):
slist.append("%s")
valuecenter=",".join(slist)
ifnotkeyinfo:
sqlcmd="insertinto%svalues(%s);"%(table,valuecenter)
else:
sqlcmd="insertinto%s%svalues(%s);"%(table,keyinfo,valuecenter)
print(sqlcmd)
print(value)
ifexecmany:
returnself.cursor.executemany(sqlcmd,value)
else:
returnself.cursor.execute(sqlcmd,value)
以上这篇浅谈MySQL在cmd和python下的常用操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。