大家現在都在利用pymysql這個包連接MySQL,然后對數據庫進行操作,網上已經有很多描述如何進行增刪改查的操作了,我這邊就直接上代碼,清晰明了;
本地連接mysql
connect = pymysql.connect(host='localhost',
port=3306,
user='u_name', #連接數據庫名稱
password='u_password', #連接數據庫密碼
db='u_db', #數據庫名稱
charset='utf8')
cursor_ins = connect.cursor() # 獲取光標
通過ssh遠程連接mysql
private_key = paramiko.RSAKey.from_private_key_file('/Users/xiaopi/.ssh/id_rsa') # mac私鑰
with SSHTunnelForwarder(
# 指定ssh登錄的跳轉機的address
ssh_address_or_host=('192.168.10.5', 22),
# 設置密鑰
ssh_pkey=private_key,
ssh_username='ssh_name',
# 設置數據庫服務地址及端口
remote_bind_address=('192.168.40.12', 3306)) as server:
conn = pymysql.connect(database='u_db',
user='u_name',
password='u_password',
host='127.0.0.1', # 因為上面沒有設置local_bind_address,所以這里必須是127.0.0.1,如果設置了,取設置的值就行了。
port=server.local_bind_port) # 這里端口也一樣,上面的server可以設置,沒設置取這個就行了
cursor_ins = conn.cursor() # 獲取光標
增(兩種方法)
# 批量插入
connect = pymysql.connect(host='localhost', port=3306, user='u_name', password='u_password', db='u_db', charset='utf8')
students = [(1,10,'男',4),(2,10,'女',4)] # 注意每個list的內容要用括號擴起來
insert_sql = "insert into student (id,age,sex,grade) values (%s,%s,%s,%s)"
cursor_ins = connect.cursor() # 獲取光標
try:
# 注意這里使用的是executemany而不是execute,下邊有對executemany的詳細說明
cursor_ins.executemany(executesql, executevalues)
connect.commit()
print(u'更新成功...')
except Exception as e:
print(u'更新錯誤...', e)
connect.rollback()
finally:
cursor_ins.close()
connect.close()
# 單條插入
connect = pymysql.connect(host='localhost', port=3306, user='u_name', password='u_password', db='u_db', charset='utf8')
insert_sql = "insert into student (id,age,sex,grade) values (%s,%s,%s,%s)"
cursor_ins = connect.cursor() # 獲取光標
try:
cursor_ins.execute(insert_sql,(3,10,'男',4))
connect.commit()
print(u'更新成功...')
except Exception as e:
print(u'更新錯誤...', e)
connect.rollback()
finally:
cursor_ins.close()
connect.close()
查、改、刪
connect = pymysql.connect(host='localhost', port=3306, user='u_name', password='u_password', db='u_db', charset='utf8')
cursor = connect.cursor() # 獲取光標
# 查詢
select_sql = "SELECT * from student"
cursor.execute(select_sql)
print(u'查詢成功...')
datas = cursor.fetchall() #獲取查詢結果
for data in datas:
print(data)
# 修改
update_sql = "UPDATE student SET grade = '5' WHERE `id` = '3'"
cursor.execute(update_sql)
connect.commit()
print(u'修改成功...')
# 刪除
delete_sql = "DELETE from student WHERE `id` = '3'"
rows = cursor.execute(delete_sql)
print("待更新行數:" + str(rows))
connect.commit()
print(u'刪除成功...')
cursor.close() #關閉光標
connect.close() #關閉連接
問題匯總
遇到一個插入時比較坑的問題在此記錄一下;
在插入數據時,如果sql語句寫成以下形式是無法插入str
類型的數據的
"insert into `student` (`id`,`age`,`sex`,`grade`) values (`%s`,`%s`,`%s`,`%s`)"
此時插入str
類型的數據會報以下錯誤:
(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '男'')' at line 1")
主要問題在sql語句中已添加了引號,在sql解析的時候會提醒多插入引號的錯誤,此時只需要將sql中的 “`”去掉即可。