import pymysql
# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', passwd="root123", charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 2.发送指令
cursor.execute("insert into admin(username,password,mobile) values('wupeiqi','qwe123','15155555555')")
conn.commit()
# 3.关闭
cursor.close()
conn.close()
pip install mysqlclient
create database gx_day15 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
在settings.py文件中进行配置和修改
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'gx_day15', # 数据库名字
'USER': 'root',
'PASSWORD': 'root123',
'HOST': '127.0.0.1', # 那台机器安装了MySQL
'PORT': 3306,
}
}
create table app01_userinfo(
id bigint auto_increment primary key,
name varchar(32),
password varchar(64),
age int
)
执行命令:
python manage.py makemigrations
python manage.py migrate
注意:app需要提前注册。
在表中新增列时,由于已存在列中可能已有数据,所以新增列必须要指定新增列对应的数据
以后在开发中如果想要对表结构进行调整:
python manage.py makemigrations
python manage.py migrate
#### 1.新建 ####
Department.objects.create(title="销售部")
Department.objects.create(title="IT部")
Department.objects.create(title="运营部")
UserInfo.objects.create(name="武沛齐", password="123", age=19)
UserInfo.objects.create(name="朱虎飞", password="666", age=29)
UserInfo.objects.create(name="吴阳军", password="666")
#### 2.删除 ####
UserInfo.objects.filter(id=3).delete()
Department.objects.all().delete()
#### 3.获取数据 ####
# 3.1 获取符合条件的所有数据
data_list = [对象,对象,对象] QuerySet类型
data_list = UserInfo.objects.all()
for obj in data_list:
print(obj.id, obj.name, obj.password, obj.age)
data_list = [对象,]
data_list = UserInfo.objects.filter(id=1)
print(data_list)
# 3.1 获取第一条数据【对象】
row_obj = UserInfo.objects.filter(id=1).first()
print(row_obj.id, row_obj.name, row_obj.password, row_obj.age)
#### 4.更新数据 ####
UserInfo.objects.all().update(password=999)
UserInfo.objects.filter(id=2).update(age=999)
UserInfo.objects.filter(name="朱虎飞").update(age=999)