【MySQL】PyCharm操作MySQL(增删改查)

本文介绍了如何在PyCharm中连接MySQL数据库,并通过实例演示了创建person表、插入数据、查询及删除操作。强调了在插入数据时应注意避免重复,以防止错误发生。

连接数据库

  • 两种“本地连接”方式:

    1. host=‘127.0.0.1’
    2. host=‘localhost’

    在这里插入图片描述

  • “远程连接”方式:
    网卡IP地址: host=‘10.36.151.86’
    在这里插入图片描述

      import pymysql
    
      # 连接一个数据库
      # 下面2种连本机方式
      # db = pymysql.connect(host='127.0.0.1', user='root', password='123456',database='test1db')
      db = pymysql.connect(host='localhost', user='root', password='123456',database='test1db')
      # 远程方式
      # db = pymysql.Connect(host='10.36.151.86', user='root', password='123456',database='test1db')
    
      #创建一个游标
      cursor = db.cursor()
    
      #sql语句
      # sql = 'select version()'
      sql = 'select user()'
    
      # 执行sql语句
      cursor.execute(sql)
    
      # 取一行结果
      result = cursor.fetchone()
    
      # 打印
      print(result)
    

创建一个person表

import pymysql

# 创建一个person表


db = pymysql.Connect(host='10.36.151.86', user='root', password='123456',database='test1db')

#创建一个游标
cursor = db.cursor()

#sql语句
sql = '''
create table person(
id int not null primary key auto_increment,
name char(20) unique,
age int,
info varchar(100)
)
'''

# 执行sql语句
cursor.execute(sql)

# 取一行结果
result = cursor.fetchone()

# 打印
print(result)

在这里插入图片描述

插入一条数据

import pymysql

#插入一条数据
db = pymysql.Connect(host='10.36.151.86', user='root', password='123456',database='test1db')

#创建一个游标
cursor = db.cursor()

#sql语句
sql = "insert into person(name,age,info) values('二哈', 18, '我家有只小二哈')"


try:
	# 执行sql语句
	cursor.execute(sql)

	# 取一行结果
 	result = cursor.fetchone()

	# 打印
	print(result)
	# 提交事务
	db.commit()

except pymysql.Error as e:
	print(e)

	# 若出现错误,则回滚
	db.rollback()

db.close()

在这里插入图片描述
注意:要是重复运行会报错,因为名字设置唯一在这里插入图片描述
在这里插入图片描述

查询

import pymysql

db = pymysql.Connect(host='10.36.151.86', user='root', password='123456',database='test1db')

#创建一个游标
cursor = db.cursor()

#sql语句
sql = "select * from person"

try:
	# 执行sql语句
	cursor.execute(sql)

	# 取全部(元组)
	result = cursor.fetchall()

	# 打印
	for person in result:
    	#print(result)
   		id1 = person[0]
    	name = person[1]
    	age = person[2]
    	info = person[3]

    	print(f"id={id1}, name={name}, age={age}, info={info}")

	# 提交事务
	db.commit()

except pymysql.Error as e:
	print(e)

	# 若出现错误,则回滚
	db.rollback()

db.close()

在这里插入图片描述

import pymysql

db = pymysql.Connect(host='10.36.151.86', user='root', password='123456',database='test1db')

#创建一个游标
cursor = db.cursor()

#sql语句-删除
sql = "delete from person where id=1"

try:
	# 执行sql语句
	count =cursor.execute(sql)

	# 打印受影响行数
	print(count)

	# 提交事务
	db.commit()

except pymysql.Error as e:
	print(e)

	# 若出现错误,则回滚
	db.rollback()

db.close()

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值