1. 方法一
pip3 config set global.index-url
https://pypi.tuna.tsinghua.edu.cn/simple
yum -y install sqlalchemy
pip3 install pandas
import pandas as pd
from sqlalchemy import create_engine
class Python_Mysql ( object ):
def __init__ ( self ):
print ( "test" )
def getEngine ( seft ):
host = input ( "sign mysql
server host:" )
username = input ( "sign mysql
username:" )
password = input ( "sign mysql
password:" )
databasename = input ( "sign
database name:" )
port = input ( "sign mysql
port:" )
engine = create_engine ( f"mysql+pymysql:// { use
rname } : { password } @ { host } :
{ port } / { databasename } " )
return engine
def querySql ( self , conn ):
sql = input ( "sign your sql:" )
return
pd . read_sql ( sql = sql , con = conn )
if __name__ == "__main__" :
demo = Python_Mysql ()
#sql=input("sign sql:")
# sql="select * from user"
rs = demo . querySql ( demo . getEngine ())
print ( rs )
2. 方法二
1. 设置清华镜像站(从国内下载安装包,提高下载和安
装速度)
2. 安装 pandas 数据分析工具 (pandas 是知名的数据分析
工具, pandas 有完整的读取数据的工具,以及
DateFrame 数据框架,用于保存从数据库中读取的数
据 )
3. 安装 pymysql 连接器( oracle 为开发者提供的 python
管理 mysql 的工具,通过这个工具,就恶意在不替原
有代码的情况下,应对数据库软件的升级)
pip3 config set global.index-url
https://pypi.tuna.tsinghua.edu.cn/simple
yum -y install pandas
yum -y install pymysql
>>> import pandas as pd
>>> import pymysql
>>> conn = pymysql . connect (
... host = '10.1.1.100' ,
... user = 'zhangmin' ,
... password = 'zhangmin' ,
... database = 'test' ,
... port = 3306
... )
>>> conn
< pymysql . connections . Connection object at
0x7f9e24ba2c88 >
>>> cursor = conn . cursor ()
>>> cursor
< pymysql . cursors . Cursor object at
0x7f9e24ba2668 >
>>> sql = "select * from user"
>>> cursor . excute ( sql )
Traceback ( most recent call last ):
File "<stdin>" , line 1 , in < module > AttributeError : 'Cursor' object has no
attribute 'excute'
>>> cursor . execute ( sql )
3
>>> cursor . description
(( 'id' , 3 , None , 11 , 11 , 0 , False ),
( 'username' , 253 , None , 180 , 180 , 0 , False ),
( 'password' , 253 , None , 180 , 180 , 0 , False ))
>>> desc = cursor . description
>>> res
3
>>> res = cursor . fetchall ()
>>> res
(( 1 , 'aaa' , '123' ), ( 8 , 'baba' , 'pipi' ),
( 20 , 'aaaaaaaa' , 'bbbbbbbb' ))
>>> desc
(( 'id' , 3 , None , 11 , 11 , 0 , False ),
( 'username' , 253 , None , 180 , 180 , 0 , False ),
( 'password' , 253 , None , 180 , 180 , 0 , False ))
>>> [ item [ 0 ] for item in desc ]
[ 'id' , 'username' , 'password' ]
>>> col = [ item [ 0 ] for item in desc ]
>>> df = pd . DataFrame ( res , columns = col )
>>> df
id username password
0 1 aaa 123
1 8 baba pipi
2 20 aaaaaaaa bbbbbbbb 总结
1. 和 shell 脚本一样 python 文件也可以称为 py 脚本,也是
将 pyhton 指令做一个集合
2. 为了脚本更加的智能化和自动化,添加选择语句(智
能)循环语句(自动化)
3. 同时为了开发效率,可读性,做了方法,类,模块
文章知识点与官方知识档案匹配,可进一步学习相关知识
Python入门技能树基本技能数据库操作440644 人正在系统学习中
实习二十八:python管理mysql
最新推荐文章于 2024-08-18 16:26:55 发布