免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 5710 | 回复: 0
打印 上一主题 下一主题

Yii连接数据库 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-01-02 00:19 |只看该作者 |倒序浏览

Yii初看了一下,还是比较适合自己的。MVC,命令行接口,这些都是我所喜欢的。
昨天在初步的YII接触上,建立了最基本的YII程序框架。今天讲述更为重要的部
分,与数据库的交互部分。
1).设置与数据库的连接:
在WebRoot/testdrive/protected/config/main.php文件的components下面,输入
db部分。如:
return array(
......
'components'=>array(
......
'db'=>array(
'connectionString'=>'sqlite:protected/data/source.db',
),
),
......
);
-备注:如果在运行时,出现下面的内容:
CException
Description
Property "CWebApplication.db" is read only.
说明你将db部分没有放在components下面,我曾经不小心在这个地方犯过错。
-对于不同的数据库连接,可以参考如下部分:
* SQLite: sqlite:/path/to/dbfile
* MySQL: mysql:host=localhost;dbname=testdb
* PostgreSQL: pgsql:host=localhost;port=5432;dbname=testdb
* SQL Server: mssql:host=localhost;dbname=testdb
* Oracle: oci:dbname=//localhost:1521/testdb
例如:
array(
......
'components'=>array(
......
'db'=>array(
'class'=>'CDbConnection',
'connectionString'=>'mysql:host=localhost;dbname=testdb',
'username'=>'root',
'password'=>'password',
'emulatePrepare'=>true, // needed by some MySQL
installations
),
),
)
2).创建一个数据库,以sqlite3为
例:WebRoot/testdrive/protected/data/source.db.
建立示例表User,以如下sql语句:
CREATE TABLE User (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
username VARCHAR(12

NOT NULL,
password VARCHAR(12

NOT NULL,
email VARCHAR(12

NOT NULL
);
试验起见,将data目录及子目录设为777权限,如sudo chmod -R 777 data
3).CRUD操作
% cd WebRoot/testdrive
% sudo YiiRoot/framework/yiic shell,注意,因为我这边/var/www/html目录为
root权限,所以必须用sudo,否则在执行其中的生成程序的时候会失败,而且最坏
的一点是失败的时候没有提示。
Yii Interactive Tool v1.0
Please type 'help' for help. Type 'exit' to quit.
>> model User
generate User.php
The 'User' class has been successfully created in the following file:
D:\wwwroot\testdrive\protected\models\User.php
If you have a 'db' database connection, you can test it now with:
$model=User::model()->find();
print_r($model);
>> crud User
generate UserController.php
generate create.php
mkdir D:/wwwroot/testdrive/protected/views/user
generate update.php
generate list.php
generate show.php
Crud 'user' has been successfully created. You may access it via:
http://hostname/path/to/index.php?r=user
4).访问页面测试:
http://hostname/testdrive/index.php?r=user
默认的登录用户名密码为admin/admin.
好了,齐活了,不同于较之前熟悉的django,他是根据数据库来生成数据逻辑。无
论如何,虽然这还是最初级的,已经算有点意思了。
可以参
考:http://www.yiiframework.com/doc/guide/zh_cn/quickstart.first-app,这
里有更详细的信息。
               
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/15586/showart_2137411.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP