Deepin 15.4 搭建LAMP环境&Python操作数据库

1.安装Apache

1
2
3
4
$ sudo apt-get install apache2
$ apache2 -v
Server version: Apache/2.4.23 (Debian)
Server built: 2016-09-29T10:03:31

执行apache2 出现bash: apache2: 未找到命令
搜索apachetcl 将其路径/usr/sbin加入到.bashrc里面即可看到版本信息

1
2
$ export PATH=/usr/sbin:$PATH
$ ~source ~/.bashrc

注:默认工程目录为:/var/www/html
然后浏览器访问:http://localhost 出现下图则安装成功.
img

2.安装PHP

1
$ sudo apt-get install php5

再重启Apache2 :

1
service apache2 restart

3.测试PHP

新建文件info.php:

1
$ vi /var/www/html/info.php

内容:<?php phpinfo(); ?>
浏览器输入:http://localhost/info.php
出现下面的图片即安装成功.
img

出现错误:
Not Found
The requested URL /test.php was not found on this server.
Apache/2.4.23 (Debian) Server at localhost Port 80
说明当前网站目录中没有test.php这个文件

4.安装MySQL

1
$ sudo apt-get install mysql-server mysql-client

New password for the MySQL “root”user:<–输入root密码
Repeat password for the MySQL “root”user:<–再输入一次

5.安装其他

1
2
3
4
$ sudo apt-get install libapache2-mod-php5
$ sudo apt-get install libapache2-mod-auth-mysql
$ sudo apt-get install php5-mysql
$ sudo apt-get install php5-gd

6.安装phpmyadmin管理Mysql

1
$ sudo apt-get install phpmyadmin

这里选择apache2
img
img
img
给phpmyadmin添加软链接:
sudo ln -s /usr/share/phpmyadmin /var/www/html

phpmyadmin测试:在浏览器地址栏中打开http://localhost/phpmyadmin 如下所示:
img
用户名初始为root密码是MySQL设置的密码,登录进来
img

7.Apache配置

启用mod_rewrite模块。

1
2
$ sudo a2enmod rewrite
$ sudo service apache2 restart

编辑/etc/apache2/apache2.conf,在最后添加一行,设置Apache支持.htm、.html和.php。

1
AddType application/x-httpd-php .php .htm .html

至此,配置完成。
——————————————————————————————————

8.Python操作数据库(CURD)

安装MySQLdb

1
$ sudo pip install mysql-python

加载包

1
2
import MySQLdb
import MySQLdb.cursors

建立连接

1
2
3
db = MySQLdb.connect(host='127.0.0.1', user='root', passwd='123456', db='douban', port=3306, charset='utf8', cursorclass=MySQLdb.cursors.DictCursor)
db.autocommit(True)
cursor = db.cursor()

以豆瓣电影数据为例对MySQL数据库进行Creat,Update,Read,Delete操作
首先在phpmyadmin里面创建数据表,如下图
img

①创建数据库,读入数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Create
fr = open('douban_movie.txt', 'r')
count = 0
for line in fr:
count += 1
print count
if count == 1:
continue
line = line.strip().split('^')
# execute()函数第一个参数为要执行的SQL命令
cursor.execute("insert into movie(name, url, score, length, description) values(%s, %s, %s, %s, %s)", [line[1], line[2], line[4], line[-3], line[-1]])
fr.close()

②更新操作

1
cursor.execute("update movie set title=%s, length=%s where id=%s", ['湄公河行动', 120, 1])

③读取数据

1
2
3
4
5
6
7
8
9
10
11
12
cursor.execute("select * from movie")
movies = cursor.fetchall()
print type(movies), len(movies), movies[0]
cursor.execute("select id, name, url from movie")
movie = cursor.fetchone()
print type(movie), len(movie), movie
cursor.execute("select id, name, url from movie order by id desc")
movie = cursor.fetchone()
print type(movie), len(movie), movie

④删除操作

1
cursor.execute("delete from movie where id=%s", [1])

img

如果文章对您有用请随意打赏,谢谢支持!
0%