shell/python 调用mysql

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w417950004/article/details/82842271

一,shell调用mysql

坑:在shell执行mysql语句的时候密码一定要与“-p”写在一起:

$MYSQL -h $HOST_NAME -u $USER -p"$PASSWORD" -e "${SHOWBASE}"
分开写会出错。

二,python调用mysql

1,python2连接mysql:

import MySQLdb
#连接数据库
conn = MySQLdb.connect(host="127.0.0.1",port=22066,user="root",passwd="123456",db="dsideal_db",charset="utf8")
#获得游标
cursor=conn.cursor()
#执行查询
n = cursor.execute("select * from result_table;")
#获取查询结果
res = cursor.fetchall()
#输出结果
for row in res:
        print("row:",row)
#关闭连接
cursor.close()

python2中使用MySQLdb来连接mysql。

2,python3 使用mysql数据库

import pymysql

def get_data_insql():
    #连接数据库
    db = pymysql.connect("10.0.0.127","username","password","database")
    #获取游标
    cursor = db.cursor()
    # 执行查询语句
    search_sql = "select * from table_name;"
    cursor.execute(search_sql)
    # 获取并打印查询结果
    res = cursor.fetchall()
    for row in res:
        print("row:",row)
        rid = row[0]
        keyw = row[1]
        print("%s\t%s" % (rid,keyw))
    #关闭连接
    db.close()

get_data_insql()

还可以使用python对mysql进行建库,插入数据,删除数据,更新数据等操作,详细见连接:

http://www.runoob.com/python3/python3-mysql.html

参考链接:https://www.cnblogs.com/clover-siyecao/p/5591992.html

猜你喜欢

转载自blog.csdn.net/w417950004/article/details/82842271