Ubuntu下MySQL+Python+pymysql 安装和简单使用

一. MySQL 安装

  • apt-get install mysql-server
  • apt-get isntall mysql-client
  • apt-get install libmysqlclient-dev
  • 上面三条指令安装完后,可以用sudo netstat -tap | grep mysql,查看是否安装成功并启动。

二. Python 安装

  • apt-get install python3.7
  • 安装成功后,直接输入命令python或者python3,即可进入python。
  • 或者用python test.py、python3 test.py来运行py文件。

三. pymysql 安装

  • 常见的Python+MySQL有:MySQLdb(python2版本支持)和PyMySQL(python3版本支持)。
  • apt-get install python-pip
  • 如果要安装python3可以用的库,要通过pip3,安装方式是:apt-get install python3-pip

四. pymysql 简单使用

1.  程序Access denied问题解决:

  • 这个过程找到了两种解决方案,但不知道是哪一种解决问题的。所以都先记录下吧
  • 方案一:

    ①登入MySQL
    ②进入你项目使用的数据库
    ③输入以下命令:
    grant usage on *.* to 你项目使用的user@localhost identified by'你的密码';
    ④最后输入:
    FLUSH PRIVILEGES;
  • 方案二:
    更换了root密码的认证方式,新版mysql使用的caching_sha2_password,换成mysql_native_password就可以连上了。

    ①登入MySQL
    ②然后输入ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'yourpasswd';

2. 使用示例

import pymysql

#连接到数据库
user_db=pymysql.connect(host='127.0.0.1',user='root',passwd='sjl1103',db='test')

#获取游标对象
cursor=user_db.cursor()

#建立一个表格
create="CREATE TABLE movie_test(M_year  VARCHAR(4),Movie VARCHAR(20),Trans VARCHAR(20),Locate VARCHAR(20),Director VARCHAR(10),Personal_Score DOUBLE,DB_Score DOUBLE)"
cursor.execute(create)
user_db.commit()

#插入内容
insert_table_sql = """\
INSERT INTO movie_test(M_year,Movie,Trans,Locate,Director,Personal_Score,DB_Score)
VALUES('{M_year}','{Movie}','{Trans}','{Locate}','{Director}','{Personal_Score}','{DB_Score}')
"""

#INSERT INTO movie_test VALUES('2018','我不是药神',' ','华语','文牧野',8.8,8.9);
#INSERT INTO movie_test VALUES('2017','Three Billboards','三块广告牌','欧美','马丁·麦克唐纳',8.7,8.7);
cursor.execute(insert_table_sql.format(M_year='2018',Movie='我不是药神',Trans=' ',Locate='华语',Director='文牧野',Personal_Score=8.8,DB_Score=8.9))

cursor.execute(insert_table_sql.format(M_year='2017',Movie='Three Billboards',Trans='三块广告牌',Locate='欧美',Director='马丁·麦克唐纳',Personal_Score=8.7,DB_Score=8.7))

user_db.commit()

#显示内容
sql_select = """SELECT * FROM movie_test"""
cursor.execute(sql_select)
result = cursor.fetchall()
for row in result:
    for each_one in row:
        print(each_one,end=' ')
        print("  ")
    print("\n")

#关闭数据库
user_db.close()

此时进入MySQL查看,发现确实有表存在:

猜你喜欢

转载自blog.csdn.net/weixin_39731083/article/details/82179263