Python with MySql in Ubuntu

本文介绍如何使用Python连接MySQL数据库,并通过实例演示创建数据库、表及插入数据的过程。
1. Install MySQLdb in ubuntu.
sudo apt-get install python-MySQLdb

2. create a new python file

vim mysql_learn.py

3. Edit the file

#!/usr/bin/env python
# coding=utf-8

import MySQLdb

# mysql user name
userName = 'root'
# mysql user password
password = 'password'

try:

    # connect to local mysql
    conn = MySQLdb.connect(host='localhost', user=userName, passwd=password, port=3306)
    cur = conn.cursor()

    # create new database 'python_test'
    cur.execute('create database if not exists python_test')
    # select the database
    conn.select_db('python_test')
    # create table with name and age.
    cur.execute('create table p_test(name varchar(20), age int)')

    value=['wangyi1e', 28]
    cur.execute('insert into p_test values(%s, %s)',value)
    
    # commit here is very import for mysql to storage the action.
    conn.commit()
    cur.close()
    conn.close()

except MySQLdb.Error, e:
    print("Call Failure %d:%s"%(e.args[0], e.args[1]))


with mysql with phpmyadmin, we can see that the table has a new row with 'wangyi1e' and 28.


要在Ubuntu上使用Python连接MySQL数据库,你需要完成几个步骤。首先确保已经安装了MySQL,并创建好需要访问的数据库及用户权限;然后通过pip安装`pymysql`或`mysql-connector-python`库,在代码里导入相应的模块并建立连接。 以下是具体的步骤: ### 1. 安装 MySQLPython 包 如果还没有安装MySQL服务器,则先运行命令行工具并输入以下命令进行安装: ```bash sudo apt-get update sudo apt-get install mysql-server python3-pip ``` 接着为方便管理可以启动服务并且设置root密码等安全选项: ```bash sudo systemctl start mysql.service sudo mysql_secure_installation # 按提示操作设定安全性配置 ``` 对于非root账户,请自行登录MySQL添加有相应权限的新用户用于后续的应用程序链接. 随后,安装合适的Python驱动包,这里我们选择`PyMySQL`(也可以选`mysql-connector`)作为例子来说明: #### 使用 pip 安装 PyMySQL 库 ```bash pip3 install pymysql # 或者如果你偏好官方提供的 connector 可以用这条指令代替上面那条: # pip3 install mysql-connector-python ``` ### 2. 编写Python脚本连接到MySQL 接下来就可以开始编写Python代码尝试连入刚才准备好的MySQL实例啦! 下面是一段简单的示例程序展示如何利用 `PyMySQL` 连接到本地的一个名为testdb的数据库,并从中获取数据表information_schema.tables的部分内容信息返回给终端打印出来查看结果是否正常工作. ```python import pymysql.cursors connection = None try: connection = pymysql.connect( host='localhost', user='your_username', # 替换为你的用户名 password='your_password', # 替换为你的密码 database='testdb', # 数据库名称 cursorclass=pymysql.cursors.DictCursor) with connection.cursor() as cursor: sql_query = "SELECT table_name FROM information_schema.tables LIMIT 5" cursor.execute(sql_query) result = cursor.fetchall() print(result) # 输出查询的结果 finally: if connection is not None and connection.open: connection.close() print("Connection closed.") ``` 请记得将上述代码片段里的`your_username`, `your_password`替换成你在MySQL中实际使用的凭据以及正确的主机地址、端口号(若不是默认值),还有想要连接的目标数据库名哦! 以上就是UbuntuPython连接至MySQL的基本流程介绍,希望对您有所帮助~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值