使用python来进行连接数据库

首先,需要导入一个pymysq模块(如果没有,需要去下载【pip install pymysql】)

import pymysql

1. 连接数据库,

conn = pymysql.connect(
    host='localhost',
    #使用localhost与本机直接连接,如果使用本机的主机名,python编译器编译的结果需要通过外网去连接,这样你就需要去设置权限:
    # 1,首先,停止mysql的服务;
    # service mysqld stop
    #   报:
    # Stopping mysqld:  [  OK  ]
    # 2,跳过密码验证
    # 执行命令行:
    # /usr/bin/mysqld_safe --skip-grant-tables
    # 报:
    # 151104 09:07:56 mysqld_safe Logging to '/var/lib/mysql/iZ23dq2wm0jZ.err'.
    # 151104 09:07:56 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
    # 第三步:无密码登录
    #   执行命令行:
    # mysql -u root
    # mysql>
    # grant all privileges on *.* to 'westos'@'station.domain1.example.com' identified by 'root' with grant option;
    # 关键词解释:
    # westos'@'station.domain1.example.com
    # station.domain1.example.com:是用户
    # westos:是密码
    #
    # 问题一:发现无密码条件下,没有授权的写权限
    # The MySQL server is running with the --skip-grant-tables option so it cannot execute this statement
    # 解决方法:
    # mysql> set global read_only=0;//(关掉新主库的只读属性)
    # mysql>flush privileges;
    # mysql>set global read_only=1;//(读写属性)
    # mysql>flush privileges;
    # (注意刷新是必须项)
    # 第五步:重启数据库
    # service mysqld stop
    # 报:
    # Stopping mysqld:  [  OK  ]
    #
    # service mysqld start
    # 报:
    # Starting mysqld:  [  OK  ]
    # 或者
    # service mysqld restart



    user='root',
    password='westos',
    db='helloTest',
    charset='utf8',
    # autocommit=True,    # 如果插入数据,, 是否自动提交? 和conn.commit()功能一致。
)
# ****python, 必须有一个游标对象, 用来给数据库发送sql语句, 并执行的.
# 2. 创建游标对象,
cur = conn.cursor()

# 3. 对于数据库进行增删改查
# 1). ************************创建数据表**********************************
try:
    create_sqli = "create table hello (id int, name varchar(30));"
    cur.execute(create_sqli) # 将create_sqli中的字符串当作命令来执行
except Exception as e:
    print("创建数据表失败:", e)
else:
    print("创建数据表成功;")


# 2). *********************插入数据****************************
try:
    insert_sqli = "insert into hello values(2, 'fensi');"
    cur.execute(insert_sqli)
except Exception as e:
    print("插入数据失败:", e)
else:
    # 如果是插入数据, 一定要提交数据, 不然数据库中找不到要插入的数据;
    conn.commit()
    print("插入数据成功;")


# 3). *********************插入多条数据****************************
try:
    info = [(i, "westos%s" %(i)) for i in range(100)]

    # *********************第一种方式********************
    # # %s必须手动添加一个字符串, 否则就是一个变量名, 会报错.
    insert_sqli = "insert into hello values(%d, '%s');"
    for item in info:
        print('insert语句:', insert_sqli %item)
        cur.execute(insert_sqli %item)

#     # *********************第二种方式********************
#     insert_sqli = "insert into hello values(%s, %s);"
#     cur.executemany(insert_sqli, info )
except Exception as e:
    print("插入多条数据失败:", e)
else:
    # 如果是插入数据, 一定要提交数据, 不然数据库中找不到要插入的数据;
    conn.commit()
    print("插入多条数据成功;")
#
#


# 4). **************************数据库查询*****************************
sqli = "select * from hello;"
result = cur.execute(sqli)  # 默认不返回查询结果集, 返回数据记录数。
print(result)
#
print(cur.fetchone())     # 1). 获取下一个查询结果集;
# print(cur.fetchone())
# print(cur.fetchone())

print(cur.fetchmany(4))   # 2). 获取制定个数个查询结果集;

# info = cur.fetchall()     # 3). 获取所有的查询结果
# print(info)
# print(len(info))

print(cur.rowcount)       # 4). 返回执行sql语句影响的行数

#  5). 移动游标指针
print(cur.fetchmany(3))
print("正在移动指针到最开始......")
cur.scroll(0, 'absolute') #将指针移动到开始位置
print(cur.fetchmany(3))
#
# print("正在移动指针到倒数第2个......")
# print(cur.fetchall())    # 移动到最后
# cur.scroll(-2, mode='relative')
#
# print(cur.fetchall())
# 4. 关闭游标
cur.close()
# 5. 关闭连接
conn.close()

猜你喜欢

转载自blog.csdn.net/qq_43279936/article/details/86519913