世纪难题,数据库终于连接上了!

在mysql中

输入:
create database mytest;
返回:
Query OK, 1 row affected (0.04 sec)

输入:
create table chengji
(name varchar(80),
grade float(80,2),
num int(80));
返回:
Query OK, 0 rows affected (0.17 sec)

以上是在数据库中创建了一个库mytest,在库中创建新表chengji

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

在python脚本中,

输入:
import pymysql as pl
name='root'
password='自己的密码'
db=pl.connect('localhost',name,password,'mytest')
返回:
pymysql.err.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: NO)")

网上给了各种各样的方法,大多是通过各种方式修改密码。捣鼓了俩多钟头,败北。
在行将放弃之际,又百度了一下,发现一篇贴,
步骤:在cmd命令行连接mysql
然后输入ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '自己密码';
再运行python脚本,连接成功。
原贴:https://blog.csdn.net/dongweionly/article/details/80273095

继续。。。。。。。。。。。

输入:
cursor = db.cursor()
# 使用 cursor() 方法创建一个游标对象 cursor,游标的概念参考https://blog.csdn.net/yxwb1253587469/article/details/52249174

cursor.execute("DROP TABLE IF EXISTS chengji")
# 使用 execute() 方法执行 chengji,如果表存在则删除

chengji='''create table chengji(
name varchar(80),
grade float(80,2),
num int(80));'''
# 创建表的预处理语句

cursor.execute(chengji)

返回:
Warning (from warnings module):
  File "D:\python\lib\site-packages\pymysql\cursors.py", line 165
    result = self._query(query)
Warning: (1051, "Unknown table 'mytest.chengji'")

创建了一个三列的表。

下面尝试存入数据
输入:
sql = """INSERT INTO chengji(
name,grade,num)
VALUES ('James', 89.1, 3);"""
cursor.execute(sql)
db.commit()
返回:>>> 

下面尝试获取数据。
输入:
sql = "SELECT * FROM chengji"

try:
   # 执行SQL语句
   cursor.execute(sql)
   # 获取所有记录列表,使用fetchall() 方法获取多条数据。
   results = cursor.fetchall()
   for row in results:
      name = row[0]
      grade = row[1]
      num = row[2]
       # 打印结果
      print (name, grade,num)
except:
   print ("Error: unable to fetch data")
返回:
============== RESTART: D:\python\pythondata\shujukuchangshi.py ==============
James 89.1 3

后面可以考虑结合前面的方法,从数据库调取数据进行统计分析。

猜你喜欢

转载自blog.csdn.net/qdu5er/article/details/81121723