Apache 配置CGI脚本操作数据库
来源:互联网 发布:约翰马尔科维奇 知乎 编辑:程序博客网 时间:2024/06/03 21:37
关于Apache的配置请先参考博文 Apache配置
本文假设我们已经配置好了一个基本的Apache服务器,接下我们就要配置如何通过CGI脚本(UNIX shell、Perl、PHP、Python等脚本语言写成的程序)去实现一个网站的后端数据库连接及简单操作
1. PHP实现
1.1. 在安装好的Apache服务其中安装配置php环境
yum install php -y
php的配置文件就不翻译了
[root@lockey html]# cat /etc/httpd/conf.d/php.conf ## Cause the PHP interpreter to handle files with a .php extension.#<FilesMatch \.php$> SetHandler application/x-httpd-php #在文件扩展名与特定的处理器之间建立映射</FilesMatch>## Allow php to handle Multiviews#AddType text/html .php## Add index.php to the list of files that will be served as directory# indexes.#DirectoryIndex index.php## Uncomment the following lines to allow PHP to pretty-print .phps# files as PHP source code:##<FilesMatch \.phps$># SetHandler application/x-httpd-php-source#</FilesMatch>## Apache specific PHP configuration options# those can be override in each configured vhost#php_value session.save_handler "files"php_value session.save_path "/var/lib/php/session"[root@lockey html]#
1.2. 安装php的数据库支持:
[root@lockey conf.d]# yum install -y php-mysql
注意:
注意当web服务器连接的数据库在远程时,需要改变Selinux:# setsebool -P httpd_can_network_connect_db=1# setsebool -P httpd_can_network_connect=1 (如果数据库的端口不是3306时,需要改此项)
重启httpd服务后,测试网页是否访问正常.
在网站根目录下建立一个php脚本文件(例如halo.php)
[root@lockey html]# cat halo.php <?phpecho "This is a test for PHP script!";?> [root@lockey html]#
1.3. 测试数据库连接
例如我们在网站根目录下建立了一个文件index.php
[root@lockey html]# cat index.php <?php$servername = "localhost";$username = "root";$password = "halo";/ 创建连接$conn = new mysqli($servername, $username, $password);// 检测连接if ($conn->connect_error) { die("连接失败: " . $conn->connect_error);} echo "连接成功";?>[root@lockey html]#
1.4. PHP简单操作数据库(创建一个数据库)
[root@lockey html]# cat halo.php <?phpecho "This is a test for PHP script!";?> [root@lockey html]# cat index.php <?php$servername = "localhost";$username = "root";$password = "halo";// 创建连接$conn = new mysqli($servername, $username, $password);// 检测连接if ($conn->connect_error) { die("连接失败: " . $conn->connect_error);}// 创建数据库$sql = "CREATE DATABASE lockeyDB";if ($conn->query($sql) === TRUE) { echo "数据库创建成功"; $sql1 = "SHOW DATABASES;"; $result = $conn->query($sql1);if ($result) { // 输出数据 var_dump($result);} else { echo "0 结果";}} else { echo "Error creating database: " . $conn->error;}$conn->close();?> [root@lockey html]#
登录数据库验证操作
[root@lockey html]# mysql -uroot -phaloWelcome to the MariaDB monitor. Commands end with ; or \g.Your MariaDB connection id is 8Server version: 5.5.52-MariaDB MariaDB ServerCopyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.MariaDB [(none)]> SHOW DATABASES;+--------------------+| Database |+--------------------+| information_schema || lockeyDB || mysql || performance_schema |+--------------------+4 rows in set (0.01 sec)MariaDB [(none)]>
2. Python实现
默认我们已经安装了Python2.X,接下来
2.1 安装Python访问mysql数据库的模块
[root@lockey cgi-bin]#yum install MySQL-python -y
模块安装验证:
没有报错,说明模块安装成功
2.2 Web CGI服务器支持及配置
[root@lockey cgi-bin]# vim /etc/httpd/conf/httpd.conf
在你进行CGI编程前,确保您的Web服务器支持CGI及已经配置了CGI的处理程序。
Apache 支持CGI 配置:
设置好CGI目录:
#确保配置文件里面有这样一行内容ScriptAlias /cgi-bin/ /var/www/cgi-bin/
运行脚本目录配置:
<Directory "/var/www/cgi-bin"> AllowOverride None Options +ExecCGI Order allow,deny Allow from all</Directory>
在 AddHandler 中添加 .py 后缀,这样我们就可以访问 .py 结尾的 python 脚本文件:
AddHandler cgi-script .cgi .pl .py
2.3 验证脚本是否正常运行
[root@lockey cgi-bin]# cat halo.py #!/usr/bin/python# -*- coding: UTF-8 -*-print "Content-type:text/html"print # 空行,告诉服务器结束头部print '<html>'print '<head>'print '<meta charset="utf-8">'print '<title>Lockey Cheng de python page</title>'print '</head>'print '<body>'print '<h2>Lockey:Halo the World!...</h2>'print '</body>'print '</html>'[root@lockey cgi-bin]# pwd/var/www/cgi-bin[root@lockey cgi-bin]#
在浏览器中访问测试ok
2.4 验证数据库连接
[root@lockey cgi-bin]# cat index.py #!/usr/bin/python# -*- coding: UTF-8 -*-#import MySQLdb# 打开数据库连接#db = MySQLdb.connect("localhost","root","halo","lockeyDB" )# 使用cursor()方法获取操作游标 #cursor = db.cursor()# 使用execute方法执行SQL语句#cursor.execute("SELECT VERSION()")# 使用 fetchone() 方法获取一条数据库。#data = cursor.fetchone()print 'halo world!';#print "Database version : %s " % data# 关闭数据库连接#db.close()[root@lockey cgi-bin]#
2.5 Python数据库操作(建表、插入数据、查数据)
[root@lockey cgi-bin]# cat hi.py #!/usr/bin/python# -*- coding: UTF-8 -*-print "Content-type:text/html"print # 空行,告诉服务器结束头部print '<html>'print '<head>'print '<meta charset="utf-8">'print '<title>lockey</title>'print '</head>'print '<body>'import MySQLdbdb = MySQLdb.connect("localhost","root","halo","lockeyDB" )# 使用cursor()方法获取操作游标 cursor = db.cursor()# 使用execute方法执行SQL语句cursor.execute("SELECT VERSION()")# 使用 fetchone() 方法获取一条数据库。data = cursor.fetchone()print '<h1>'print "Database version : %s " % data# 如果数据表已经存在使用 execute() 方法删除表。print '</h1>'cursor.execute("DROP TABLE IF EXISTS User")# 创建数据表SQL语句sql = """CREATE TABLE User ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )"""cursor.execute(sql)sql1 = """INSERT INTO User(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""try: # 执行sql语句 cursor.execute(sql1) # 提交到数据库执行 db.commit()except: # Rollback in case there is any error db.rollback()sql2 = "SELECT * FROM User \ WHERE INCOME > '%d'" % (1000)try: # 执行SQL语句 cursor.execute(sql2) # 获取所有记录列表 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=%d,sex=%s,income=%d" % \ (fname, lname, age, sex, income )except: print "Error: unable to fecth data"# 关闭数据库连接db.close()print '<h2>database test</h2>'print '</body>'print '</html>'[root@lockey cgi-bin]#
OK,Aache 配置Python操作数据库over!
阅读全文
1 0
- Apache 配置CGI脚本操作数据库
- Apache 配置CGI脚本操作数据库之Perl操作
- Apache Web 服务器配置CGI程序,执行Python、Perl脚本
- Windows下配置Apache运行C语言的CGI脚本
- apache配置cgi
- apache 配置 python cgi
- ubuntu+apache+cgi配置
- apache配置CGI
- 配置apache支持cgi
- ubuntu apache cgi 配置
- Apache配置CGI
- 配置Apache 运行CGI
- Windows 配置Apache+CGI
- Linux Apache CGI 配置
- linux Apache CGI 安装配置
- 配置apache运行cgi程序
- mac下 apache cgi 配置
- Apache Tomcat 容器配置CGI
- Bootstrap 文本域大小固定
- PrintStream输出流
- 2017.8.12总结
- (poj 3667 Hotel)<丧病线段树区间合并>
- 训练日记8.12
- Apache 配置CGI脚本操作数据库
- 观察者模式
- java基础
- 生产者消费者模式
- 记忆化搜索之P1464 Function
- Spring入门介绍
- OpenCV结合socket进行实时视频传输(TCP协议)
- 线程基础/线程同步和互斥
- Atcoder Transit Tree Path