SOP:Ubuntu中pymysql和mysql安装

SOP:Ubuntu中pymysql和mysql安装

  • 问题
  • 解决

问题

  • 最后容易连接不上

解决

  • 安装pymysql
pip install pymysql
  • 安装mysql
    链接

  • test

CREATE DATABASE pytest;

USE pytest;

CREATE TABLE student(
NAME VARCHAR(20),
age INT
);

DELETE FROM student;

INSERT INTO student(NAME,age) VALUES('zhangshan',20);
INSERT INTO student(NAME,age) VALUES('lisi',88);

  • 连接 需要设置root密码
    链接
  • 注意中间一行需要换成
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '123';
  • test
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import pymysql
#连接数据库
conn = pymysql.connect(user='root',password='root',database='pytest',charset='utf8')
cur = conn.cursor()

#不论是什么数据类型,占位符都用%s
#带条件查询
sql = ('SELECT * FROM student WHERE NAME =%s AND age =%s')
cur.execute(sql,('zhangshan',20))
#不带条件查询
sql = ('SELECT * FROM student')
cur.execute(sql)

#将只返回一条结果,返回单个元组如('name','age')
#data = cur.fetchone()
#也将返回所有结果,返回二维元组(tuple),如(('name','age'),('name','age'))
data = cur.fetchall()

#打印值
for (name,age) in data:
 print(name,age)
 
#新增
sql=('INSERT INTO student VALUES(%s,%s)')
cur.execute(sql,('wangwu',10))

#修改
sql=('UPDATE student SET age=%s WHERE NAME=%s')
cur.execute(sql,(20,'wangwu'))

#删除
sql=('DELETE FROM student WHERE NAME =%s')
cur.execute(sql,('wangwu'))
#只要是修改了表内容的操作,后面一定要提交,否则不起作用新增修改删除
conn.commit()

conn.close
cur.close


你可能感兴趣的:(mysql,ubuntu,数据库)