pycharm 里面引用pymysql

import pymysql
db =pymysql.connect(host ='192.168.1.131',port=3306,user='jack',password ='jack',db ='db')
cur = db.cursor()
#cur.execute("create table t1(id int)")
cur.execute('insert into t1(id) VALUES (2)')
db.commit()    # 这里是db来commit,而不是cur,达到刷新到数据库的目的。
cur.execute("select *  from t1")
a = cur.fetchall()
for i in a:
    print(i)

一下内容转自网友的:https://www.cnblogs.com/liuzhongchao/p/8315713.html,版权归属原作者。

pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。但目前pymysql支持python3.x,而MySQLdb不支持3.x版本。

1.通过 pip 安装 pymysql

进入 cmd  输入  pip install pymysql  
回车等待安装完成;
 

2.测试连接

>>> import pymysql      #导入 pymysql ,如果编译未出错,即表示 pymysql 安装成功
 

3.pymysql操作

表结构如下:

3.1查询操作

复制代码
import pymysql  #导入 pymysql

#打开数据库连接
db= pymysql.connect(host="localhost",user="root", password="123456",db="test",port=3307) # 使用cursor()方法获取操作游标 cur = db.cursor() #1.查询操作 # 编写sql 查询语句 user 对应我的表名 sql = "select * from user" try: cur.execute(sql) #执行sql语句  results = cur.fetchall() #获取查询的所有记录 print("id","name","password") #遍历结果 for row in results : id = row[0] name = row[1] password = row[2] print(id,name,password) except Exception as e: raise e finally: db.close() #关闭连接
复制代码

3.2插入操作

复制代码
import pymysql
#2.插入操作
db= pymysql.connect(host="localhost",user="root", password="123456",db="test",port=3307) # 使用cursor()方法获取操作游标 cur = db.cursor() sql_insert ="""insert into user(id,username,password) values(4,'liu','1234')""" try: cur.execute(sql_insert) #提交  db.commit() except Exception as e: #错误回滚  db.rollback() finally: db.close()
复制代码

3.3更新操作

复制代码
更新操作
db= pymysql.connect(host="localhost",user="root", password="123456",db="test",port=3307) # 使用cursor()方法获取操作游标 cur = db.cursor() sql_update ="update user set username = '%s' where id = %d" try: cur.execute(sql_update % ("xiongda",3)) #像sql语句传递参数 #提交  db.commit() except Exception as e: #错误回滚  db.rollback() finally: db.close()
复制代码

3.4删除操作

复制代码
import pymysql
#4.删除操作
db= pymysql.connect(host="localhost",user="root", password="123456",db="test",port=3307) # 使用cursor()方法获取操作游标 cur = db.cursor() sql_delete ="delete from user where id = %d" try: cur.execute(sql_delete % (3)) #像sql语句传递参数 #提交  db.commit() except Exception as e: #错误回滚  db.rollback() finally: db.close()

猜你喜欢

转载自www.cnblogs.com/kaishirenshi/p/10057546.html