參考資料:
這裡使用的是庫是pymysql
python鏈結資料庫時,mysql中要有要連線的資料庫,否則會無法連線。
import pymysql
#import movie
host =
'localhost'
#主機名
user =
'root'
#使用者名稱
password =
''#密碼
database =
'douban2'
#資料庫名
#建表def
create_table()
: db=pymysql.connect(host,user,password,database)
cursor=db.cursor(
) cursor.execute(
"drop table if exists contents"
) sql=
""" create table contents(
movie_id char(60) not null,
movie_title char(200),
movie_director char(200),
movie_screenwriter char(200),
movie_character varchar(1000),
movie_type char(200),
movie_country char(200)
) """
cursor.execute(sql)
db.commit(
) db.close(
)#建表
defcreate_table_comment()
: db=pymysql.connect(host,user,password,database)
cursor=db.cursor(
) cursor.execute(
"drop table if exists comment"
) sql=
""" create table comment(
movie_id char(60) not null,
movie_comment text
) """
cursor.execute(sql)
db.commit(
) db.close(
)#插入資料
definsert_database(id
,title,director,screenwriter,mcharacter,mtype,country)
: db=pymysql.connect(host,user,password,database)
cursor=db.cursor(
) sql=
' insert into contents values("%s","%s","%s","%s","%s","%s","%s")'\
%(id
,title,director,screenwriter,mcharacter,mtype,country)
try:
cursor.execute(sql)
db.commit(
)except
: db.rollback(
) db.close(
)#插入資料
definsert_comment(id
,comment)
: db=pymysql.connect(host,user,password,database)
cursor=db.cursor(
) sql=
' insert into comment values("%s","%s")'\
%(id
,comment)
try:
cursor.execute(sql)
db.commit(
)except
: db.rollback(
) db.close(
)#查詢資料
defselect_database(id
):db = pymysql.connect(host, user, password, database)
cursor = db.cursor(
) sql=
'select movie_id from contents ' \
'where movie_id="%s"'%id
try:
cursor.execute(sql)
results=cursor.fetchall(
)for row in results:
m_id=row[0]
print((
"movie_id=%s"
)%m_id +
'ok!'
+'\n'
)except
:print
("error:unable to fetch"+id
) db.close(
)
python鏈結mysql資料庫
安裝mysql python包 sudo apt get install python mysqldb在程式中使用 db connect url,user,password,database cursor db.cursor 獲取游標 sql create table employee first ...
python鏈結MySQL資料庫
python鏈結mysql資料庫。用到mysqldb庫,安裝 pip install mysql python 我這邊安裝完報錯 error command c program files microsoft visual studio 14.0 vc bin cl.exe failed with ...
python自學(三)鏈結mysql,查詢資料
1 安裝mysql python 1.2.5.win32 py2.7 2 安裝是發現之前安裝的python版本是3.6.0,但是mysql驅動只支援道2.7,沒辦法,解除安裝重新安裝,也好,加深印象。3 安裝python2.7後成功安裝mysql python 1.2.5.win32 py2.7,e...