標籤:test group 結果 sele 指定位置 std __name__ truncate varchar
一、遊標
遊標(Cursor)是處理資料的一種方法,為了查看或者處理結果集中的資料,遊標提供了在結果集中一次一行或者多行前進或向後瀏覽資料的能力。可以把遊標當作一個指標,它可以指定結果中的任何位置,然後允許使用者對指定位置的資料進行處理。
模版案例一、
Import…………
if __name__ == ‘__main__‘:
cnx = connect_mysql()
cus = cnx.cursor()
sql = ‘‘‘ create table test(id int not null);insert into test(id) values (100);‘‘‘
try:
cus.execute(sql)
cus.close()
cnx.commit()
except Exception as e:
cnx.rollback()
print(‘Error‘)
# raise e
finally:
cnx.close()
案例二如下:
import pymysql
# 建立串連
conn = pymysql.connect(host="192.168.48.136", port=3306, user="xiang", passwd="xiang", db="test")
# 建立遊標
cus = conn.cursor()
# 定義sql
sql = "select * from test2;"
# 執行
# cus.execute(sql)
# 取所有的結果,取結果之前,一定要先執行sql
# cus.fetchall()
# 取一個結果
# cus.fetchone()
# 取10行資料
# cus.fetchmany(size=10)
# 關閉遊標
# cus.close()
# cus.executemany()
try:
cus.execute(sql)
result = cus.fetchone()
print(result)
except Exception as e:
raise e
finally:
cus.close()
conn.close()
二、建立表,常用命令。
1.建立表命令如下。
案例三
create table 表名(
列名 資料類型 not null
………………
);
create table Stdunet(
stdId int not null,
stdname varchar(100),
age int,
sex enum(‘M‘, ‘F‘),
score int);
‘123‘ varchar(10)
‘123 ‘ char(10)
課堂錯誤修正案例四、
grant all privileges on *.* to ‘user1‘@‘%‘ identified by ‘123456‘ with grant option;
你這個user1使用者,只能對所有的庫,所有的表進行增刪改查等,沒有對其他使用者進行授權 user2就沒法授權
2.常用命令。
1>.select 列名 from 表名 where 條件判斷
select * from sutdent where group by stdname
a, c where a.id = c.組id
select a.id a.name, c.id from a join c on c.組id = a.id and ^^^^
select * from table_name limiet 10;
show create table_name
desc table_name
2>.insert into table_name (id, name, age) values(1, ‘ling‘, 18), (), (), ();
3>.delete from table where 條件判斷
4>truncate 只清楚資料,不刪除表結構
drop 表結果都給你幹掉了
5>.update table_name set 列名=xxx, where 條件
6>.create index 庫名_表名_列名1_列名2 (列名1, 列名2)
mysql常用命令