Python --链接MYSQL数据库与简单操作 含SSH链接

项目是软硬件结合,在缺少设备的情况,需要通过接口来模拟实现与设备的交互,其中就需要通过从数据库读取商品的ID信息

出于安全考虑  现在很多数据库都不允许通过直接访问,大多数是通过SSH

SSH : 数据库开放哪台机器访问,就通过哪台机器的SSH跳过去

例如:数据库在A机器,只能通过B来访问,本机C来链接B链接A的数据库

链接数据库与简单操作:

链接数据库:
import MySQLdb
#打开数据库链接
lcDB = MySQLdb.connect("127.0.0.1", "%,"123456","go" )

简单数据库操作:

创建数据库表:
 1 import MySQLdb
 2 #打开数据库链接
 3 lcDB = MySQLdb.connect("127.0.0.1", "root","123456","test" )
 4 #使用cursor()方法获取操作游标
 5 cursor = lcDB.cursor()
 6 
 7 #使用execute方法执行SQL语句
 8 cursor.execute('select version()') #查询MYSQL版本
 9 
10 #使用fetchone()方法获取一条数据
11 data = cursor.fetchone()
12 
13 print("Database version : %s"%data)
14 
15 #使用 execute()方法执行SQL,如果表存在则删除
16 cursor.execute("DROP TABLE if exists employee")
17 
18 #使用预处理语句创建表
19 sql = """create table employee( 
20         first_name char(20) not null,
21         last_name char(20),
22         age int,
23         sex char(1),
24         income float
25         )"""
26 
27 cursor.execute(sql)
28 
29 #关闭数据库链接
30 lcDB.close()

执行结果:

Database version : 8.0.11
数据库:

 插入数据:

import  pymysql

#打开数据库链接
lcDB = pymysql.connect("127.0.0.1", "root", "123456", "test")

#使用cursor()方法创建一个游标对象cursor
cursor = lcDB.cursor()

#SQL 插入语句
#此处可将SQL换位update, delete等语句
sql = "insert into employee(first_name,
        last_name, age, sex, income)
        values ('%s', '%s', '%s','%s', '%s')"% 
        ('li', 'Mohan', 20, 'M', 1000)

try:
    # 使用execute()方法执行sql,
    cursor.execute(sql)
    #提交到数据库执行sql语句
   lcDB.commit()

except:
  
#发生错误时回滚
  lcDB.rollback()

#关闭数据库
lcDB.close()

数据库查询操作

Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。

  • fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
  • fetchall():接收全部的返回结果行.
  • rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。
import  pymysql

#打开数据库链接
lcDB = pymysql.connect("127.0.0.1", "root", "123456", "test")

#使用cursor()方法创建一个游标对象cursor
cursor = lcDB.cursor()

#SQL 插入语句
#此处可将SQL换位update, delete等语句
sql = "select * from employee where income > %s"%(2000)



try:
    # 使用execute()方法执行sql,
    cursor.execute(sql)
    #获取所有记录列表
    results = cursor.fetchall()
    for row in results:
        fname = row[0]
        lname = row[1]
        age = row[2]
        sex = row[3]
        income = row[4]
        #打印结果
        print("fname = %s, lname = %s, age = %s, sex = %s,income = %s" % 
              (fname, lname,age, sex, income))

except:
    print("ERROr: unable to fecth data")


#关闭数据库
lcDB.close()
SSH链接:

  -使用mysqldb模块通过ssh隧道连接mysql

import  pymysql
from sshtunnel import SSHTunnelForwarder

server =  SSHTunnelForwarder(
    ("132.223.3.23", 19), #ssh IP和port
    ssh_password = "123123",#ssh 密码
    ssh_username = "root",#ssh账号
    remote_bind_address = ("1.1.1.1", 3306)) #数据库所在的IP和端口


#启动服务 server.start() #打印本地端口,已检查是否配置正确 print(server.local_bind_host) goDB = pymysql.connect(host = "127.0.0.1", #固定写法 port = server.local_bind_port, user = "root", #数据库账号 passwd = "2345",#数据库密码 db = "指定数据库名字")# 可以限定,只访问特定的数据库,否则需要在mysql的查询或者操作语句中,指定好表名 cur = goDB.cursor() sql = "select no from gds order by rand() limit 10" #限制每次随机查询10条数据 try: #执行SQL语句检查是否连接成功 cur.execute("select version()") result = cur.fetchone() print("Database version: %s" % result) cur.execute(sql) data = cur.fetchall() for row in data: good_no = row[0] print(good_no) except: print("Error") #关闭连接 goDB.close() server.close()
原文地址:https://www.cnblogs.com/shoebill/p/10831218.html