Java教程

pdo操作数据库

本文主要是介绍pdo操作数据库,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.连接数据库

/* 通过调用驱动程序创建一个PDO实例 */
$dsn = 'mysql:dbname=lv;host=127.0.0.1';
$user = 'root';
$password = 'root';
try {
    $pdo = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

2.查询数据库

/* 通过调用驱动程序创建一个PDO实例 */
$dsn = 'mysql:dbname=lv;host=127.0.0.1';
$user = 'root';
$password = 'root';
try {
    $pdo = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
$sql = "insert into aaaaa ('name','email') values ('xiaoming','1647114924@qq.com')";
$select = "select * from aaaaa where id=1";
$prepare = $pdo->prepare($select);
$request = $prepare->execute();
$a = $prepare->fetch(PDO::FETCH_ASSOC);
var_dump($a);

 

 3.删除一条数据

$delete = "delete from bbb where id=1";
$ac = $pdo->exec($delete);
if($ac){
    echo "删除成功";
}else{
    echo "删除失败";
}

 

 

4.修改一条数据

$update = "update bbb set name='daming',email='aaa' where id=1";
$ss = $pdo->exec($update);
if($ss){
    echo "修改成功";
}else{
    echo "修改失败";
}

 

 5.增加一条数据

$sql = "insert into bbb (user_name,user_gender) values ('aa44','vv66')";
$pp=$pdo->exec($sql);
if($pp){
    echo "添加成功";
}else{
    echo "添加失败";

6.连接数据库 (增,删,改,查)

/* 通过调用驱动程序创建一个PDO实例 */
$dsn = 'mysql:dbname=lv;host=127.0.0.1';
$user = 'root';
$password = 'root';
try {
    $pdo = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
//添加一条数据
$sql = "insert into bbb (user_name,user_gender) values ('aa44','vv66')";
$pp=$pdo->exec($sql);
if($pp){
    echo "添加成功";
}else{
    echo "添加失败";
}
//查询一条数据
$select = "select * from bbb where id=2";
$prepare = $pdo->prepare($select);
$request = $prepare->execute();
$a = $prepare->fetch(PDO::FETCH_ASSOC);
var_dump($a);

//更新一条数据
$update = "update bbb set name='daming',email='aaa' where id=1";
$ss = $pdo->exec($update);
if($ss){
    echo "修改成功";
}else{
    echo "修改失败";
}

//删除一条数据
$delete = "delete from bbb where id=1";
$ac = $pdo->exec($delete);
if($ac){
    echo "删除成功";
}else{
    echo "删除失败";
}

 

这篇关于pdo操作数据库的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!