首页 > 代码库 > python连接mysql数据库

python连接mysql数据库

1.系统必须安装MySQL-python软件,否则python没有连接的模块(在Linux系统)

yum install MySQL-python

2.安装mysql数据库

yum install mysql-server mysql

[root@AY140528120357495c4bZ ~]# /etc/init.d/mysqld restart

Stopping mysqld:                                           [  OK  ]
Starting mysqld:                                           [  OK  ]

[root@AY140528120357495c4bZ ~]#

3.在mysql中创建数据库和表

[root@AY140528120357495c4bZ ~]# mysql -u root -p
Enter password:
mysql: Unknown OS character set ‘GB18030‘.
mysql: Switching to the default character set ‘latin1‘.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 474
Server version: 5.6.11 Source distribution

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type ‘help;‘ or ‘\h‘ for help. Type ‘\c‘ to clear the current input statement.

mysql> create database tong;               --创建数据库

Query OK, 1 row affected (0.00 sec)

mysql> \u tong
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> create table t(a int);             --创建表
Query OK, 0 rows affected (0.06 sec)

mysql>
4.用python语言插入数据和查询数据

vim 1.py

import os,sys
import MySQLdb
try:
        conn=MySQLdb.connect(host="localhost",user="root",passwd="archermind",db="tong")  --输出数据库的用户名,密码,数据库名
except Exception,e:
        print(e)
        sys.exit()
cursor=conn.cursor()
sql1="insert into t values(1),(2)"    --要执行的sql语句
sql2="commit"                         --sql语句执行后必须提交事物
try:
        cursor.execute(sql1)          --执行sql语句
        cursor.execute(sql2)
except Exception,e:
        print(e)
sql3="select * from t"     --查询数据
cursor.execute(sql3)       --执行查询的语句
row=cursor.fetchall()
if row:
        for x in row:
                print(x[0])      --把值输出到屏幕上
        cursor.close()
        conn.close()

5.执行python程序,测试是否成功

[root@AY140528120357495c4bZ script]# python 8.py     --验证成功
1
2

[root@AY140528120357495c4bZ script]# mysql -u root -p tong
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 522
Server version: 5.6.11 Source distribution

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type ‘help;‘ or ‘\h‘ for help. Type ‘\c‘ to clear the current input statement.

mysql> select * from t;            --数据库里也有数据
+------+
| a    |
+------+
|    1 |
|    2 |
+------+
2 rows in set (0.00 sec)

mysql>

 

本文出自 “一起走过的日子” 博客,转载请与作者联系!