本文目錄一覽:
python如何使用pymysql連接資料庫封裝類
1、python安裝目錄設定為d:/python34
2、pymysql安裝方法為:解壓下載的文件,在cmd中運行: python setup.py install。
檢驗安裝安裝是否成功的方法:import pymysql 。 如果不報錯 說明安裝成功。
3、mysql安裝目錄為D:/phpStudy/MySQL。為避免更多配置問題,可在啟動phpstudy後,將其設為系統服務
4、基本操作:
(1)導入pymysql: import pymysql
(2)連接資料庫:
conn=pymysql.connect(host=’localhost’,user=’root’,passwd=’root’,db=’ere’,charset=’utf8′)
務必注意各等號前面的內容!charset參數可避免中文亂碼
(3)獲取操作游標:cur=conn.cursor()
(4)執行sql語句,插入記錄:sta=cur.execute(“insert 語句”) 執行成功後sta值為1。更新、刪除語句與此類似。
(5)執行sql語句,查詢記錄:cur.execute(“select語句”) 執行成功後cur變數中保存了查詢結果記錄集,然後再用循環列印結果:
for each in cur:
print(each[1].decode(‘utf-8’)) # each[1] 表示當前游標所在行的的第2列值,如果是中文則需要處理編碼
php實現mysql封裝類示例
php封裝mysql類
複製代碼
代碼如下:
?php
class
Mysql
{
private
$host;
private
$user;
private
$pwd;
private
$dbName;
private
$charset;
private
$conn
=
null;
public
function
__construct()
{
$this-host
=
‘localhost’;
$this-user
=
‘root’;
$this-pwd
=
‘root’;
$this-dbName
=
‘test’;
$this-connect($this-host,$this-user,$this-pwd);
$this-switchDb($this-dbName);
$this-setChar($this-charset);
}
//負責鏈接
private
function
connect($h,$u,$p)
{
$conn
=
mysql_connect($h,$u,$p);
$this-conn
=
$conn;
}
//負責切換資料庫
public
function
switchDb($db)
{
$sql
=
‘use’
.
$db;
$this-query($sql);
}
//負責設置字符集
public
function
setChar($char)
{
$sql
=
‘set
names’
.
$char;
$this-query($sql);
}
//負責發送sql查詢
public
function
query($sql)
{
return
mysql_query($sql,$this-conn);
}
//負責獲取多行多列的select結果
public
function
getAll($sql)
{
$list
=
array();
$rs
=
$this-query($sql);
if
(!$rs)
{
return
false;
}
while
($row
=
mysql_fetch_assoc($rs))
{
$list[]
=
$row;
}
return
$list;
}
public
function
getRow($sql)
{
$rs
=
$this-query($sql);
if(!$rs)
{
return
false;
}
return
mysql_fetch_assoc($rs);
}
public
function
getOne($sql)
{
$rs
=
$this-query($sql);
if
(!$rs)
{
return
false;
}
return
mysql_fetch_assoc($rs);
return
$row[0];
}
public
function
close()
{
mysql_close($this-conn);
}
}
echo
‘pre’;
$mysql
=
new
Mysql();
print_r($mysql);
$sql
=
“insert
into
stu
values
(4,’wangwu’,’99998′)”;
if($mysql-query($sql)){
echo
“query成功”;
}else
{
echo
“失敗”;
}
echo
“br
/”;
$sql
=
“select
*
from
stu”;
$arr
=
$mysql-getAll($sql);
print_r($arr);
?
PHP訪問MYSQL資料庫封裝類(附函數說明)
複製代碼
代碼如下:
?php
/*
MYSQL
資料庫訪問封裝類
MYSQL
數據訪問方式,php4支持以mysql_開頭的過程訪問方式,php5開始支持以mysqli_開頭的過程和mysqli面向對象
訪問方式,本封裝類以mysql_封裝
數據訪問的一般流程:
1,連接資料庫
mysql_connect
or
mysql_pconnect
2,選擇資料庫
mysql_select_db
3,執行SQL查詢
mysql_query
4,處理返回的數據
mysql_fetch_array
mysql_num_rows
mysql_fetch_assoc
mysql_fetch_row
etc
*/
class
db_mysql
{
var
$querynum
=
;
//當前頁面進程查詢資料庫的次數
var
$dblink
;
//資料庫連接資源
//鏈接資料庫
function
connect($dbhost,$dbuser,$dbpw,$dbname=”,$dbcharset=’utf-8′,$pconnect=0
,
$halt=true)
{
$func
=
empty($pconnect)
?
‘mysql_connect’
:
‘mysql_pconnect’
;
$this-dblink
=
@$func($dbhost,$dbuser,$dbpw)
;
if
($halt
!$this-dblink)
{
$this-halt(“無法鏈接資料庫!”);
}
//設置查詢字符集
mysql_query(“SET
character_set_connection={$dbcharset},character_set_results={$dbcharset},character_set_client=binary”,$this-dblink)
;
//選擇資料庫
$dbname
@mysql_select_db($dbname,$this-dblink)
;
}
//選擇資料庫
function
select_db($dbname)
{
return
mysql_select_db($dbname,$this-dblink);
}
//執行SQL查詢
function
query($sql)
{
$this-querynum++
;
return
mysql_query($sql,$this-dblink)
;
}
//返回最近一次與連接句柄關聯的INSERT,UPDATE
或DELETE
查詢所影響的記錄行數
function
affected_rows()
{
return
mysql_affected_rows($this-dblink)
;
}
//取得結果集中行的數目,只對select查詢的結果集有效
function
num_rows($result)
{
return
mysql_num_rows($result)
;
}
//獲得單格的查詢結果
function
result($result,$row=0)
{
return
mysql_result($result,$row)
;
}
//取得上一步
INSERT
操作產生的
ID,只對錶有AUTO_INCREMENT
ID的操作有效
function
insert_id()
{
return
($id
=
mysql_insert_id($this-dblink))
=
?
$id
:
$this-result($this-query(“SELECT
last_insert_id()”),
0);
}
//從結果集提取當前行,以數字為key表示的關聯數組形式返回
function
fetch_row($result)
{
return
mysql_fetch_row($result)
;
}
//從結果集提取當前行,以欄位名為key表示的關聯數組形式返回
function
fetch_assoc($result)
{
return
mysql_fetch_assoc($result);
}
//從結果集提取當前行,以欄位名和數字為key表示的關聯數組形式返回
function
fetch_array($result)
{
return
mysql_fetch_array($result);
}
//關閉鏈接
function
close()
{
return
mysql_close($this-dblink)
;
}
//輸出簡單的錯誤html提示信息並終止程序
function
halt($msg)
{
$message
=
“html\nhead\n”
;
$message
.=
“meta
content=’text/html;charset=gb2312’\n”
;
$message
.=
“/head\n”
;
$message
.=
“body\n”
;
$message
.=
“資料庫出錯:”.htmlspecialchars($msg).”\n”
;
$message
.=
“/body\n”
;
$message
.=
“/html”
;
echo
$message
;
exit
;
}
}
?
求個好用的php mysql封裝類
?php
class MMysql {
protected static $_dbh = null; //靜態屬性,所有資料庫實例共用,避免重複連接資料庫
protected $_dbType = ‘mysql’;
protected $_pconnect = true; //是否使用長連接
protected $_host = ‘localhost’;
protected $_port = 3306;
protected $_user = ‘root’;
protected $_pass = ‘root’;
protected $_dbName = null; //資料庫名
protected $_sql = false; //最後一條sql語句
protected $_where = ”;
protected $_order = ”;
protected $_limit = ”;
protected $_field = ‘*’;
protected $_clear = 0; //狀態,0表示查詢條件乾淨,1表示查詢條件污染
protected $_trans = 0; //事務指令數
/**
* 初始化類
* @param array $conf 資料庫配置
*/
public function __construct(array $conf) {
class_exists(‘PDO’) or die(“PDO: class not exists.”);
$this-_host = $conf[‘host’];
$this-_port = $conf[‘port’];
$this-_user = $conf[‘user’];
$this-_pass = $conf[‘passwd’];
$this-_dbName = $conf[‘dbname’];
//連接資料庫
if ( is_null(self::$_dbh) ) {
$this-_connect();
}
}
/**
* 連接資料庫的方法
*/
protected function _connect() {
$dsn = $this-_dbType.’:host=’.$this-_host.’;port=’.$this-_port.’;dbname=’.$this-_dbName;
$options = $this-_pconnect ? array(PDO::ATTR_PERSISTENT=true) : array();
try {
$dbh = new PDO($dsn, $this-_user, $this-_pass, $options);
$dbh-setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //設置如果sql語句執行錯誤則拋出異常,事務會自動回滾
$dbh-setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //禁用prepared statements的模擬效果(防SQL注入)
} catch (PDOException $e) {
die(‘Connection failed: ‘ . $e-getMessage());
}
$dbh-exec(‘SET NAMES utf8’);
self::$_dbh = $dbh;
}
/**
* 欄位和表名添加 `符號
* 保證指令中使用關鍵字不出錯 針對mysql
* @param string $value
* @return string
*/
protected function _addChar($value) {
if (‘*’==$value || false!==strpos($value,'(‘) || false!==strpos($value,’.’) || false!==strpos($value,’`’)) {
//如果包含* 或者 使用了sql方法 則不作處理
} elseif (false === strpos($value,’`’) ) {
$value = ‘`’.trim($value).’`’;
}
return $value;
}
/**
* 取得數據表的欄位信息
* @param string $tbName 表名
* @return array
*/
protected function _tbFields($tbName) {
$sql = ‘SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=”‘.$tbName.'” AND TABLE_SCHEMA=”‘.$this-_dbName.'”‘;
$stmt = self::$_dbh-prepare($sql);
$stmt-execute();
$result = $stmt-fetchAll(PDO::FETCH_ASSOC);
$ret = array();
foreach ($result as $key=$value) {
$ret[$value[‘COLUMN_NAME’]] = 1;
}
return $ret;
}
/**
* 過濾並格式化數據表欄位
* @param string $tbName 數據表名
* @param array $data POST提交數據
* @return array $newdata
*/
protected function _dataFormat($tbName,$data) {
if (!is_array($data)) return array();
$table_column = $this-_tbFields($tbName);
$ret=array();
foreach ($data as $key=$val) {
if (!is_scalar($val)) continue; //值不是標量則跳過
if (array_key_exists($key,$table_column)) {
$key = $this-_addChar($key);
if (is_int($val)) {
$val = intval($val);
} elseif (is_float($val)) {
$val = floatval($val);
} elseif (preg_match(‘/^\(\w*(\+|\-|\*|\/)?\w*\)$/i’, $val)) {
// 支持在欄位的值裡面直接使用其它欄位 ,例如 (score+1) (name) 必須包含括弧
$val = $val;
} elseif (is_string($val)) {
$val = ‘”‘.addslashes($val).'”‘;
}
$ret[$key] = $val;
}
}
return $ret;
}
/**
* 執行查詢 主要針對 SELECT, SHOW 等指令
* @param string $sql sql指令
* @return mixed
*/
protected function _doQuery($sql=”) {
$this-_sql = $sql;
$pdostmt = self::$_dbh-prepare($this-_sql); //prepare或者query 返回一個PDOStatement
$pdostmt-execute();
$result = $pdostmt-fetchAll(PDO::FETCH_ASSOC);
return $result;
}
/**
* 執行語句 針對 INSERT, UPDATE 以及DELETE,exec結果返回受影響的行數
* @param string $sql sql指令
* @return integer
*/
protected function _doExec($sql=”) {
$this-_sql = $sql;
return self::$_dbh-exec($this-_sql);
}
/**
* 執行sql語句,自動判斷進行查詢或者執行操作
* @param string $sql SQL指令
* @return mixed
*/
public function doSql($sql=”) {
$queryIps = ‘INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|LOAD DATA|SELECT .* INTO|COPY|ALTER|GRANT|REVOKE|LOCK|UNLOCK’;
if (preg_match(‘/^\s*”?(‘ . $queryIps . ‘)\s+/i’, $sql)) {
return $this-_doExec($sql);
}
else {
//查詢操作
return $this-_doQuery($sql);
}
}
/**
* 獲取最近一次查詢的sql語句
* @return String 執行的SQL
*/
public function getLastSql() {
return $this-_sql;
}
/**
* 插入方法
* @param string $tbName 操作的數據表名
* @param array $data 欄位-值的一維數組
* @return int 受影響的行數
*/
public function insert($tbName,array $data){
$data = $this-_dataFormat($tbName,$data);
if (!$data) return;
$sql = “insert into “.$tbName.”(“.implode(‘,’,array_keys($data)).”) values(“.implode(‘,’,array_values($data)).”)”;
return $this-_doExec($sql);
}
/**
* 刪除方法
* @param string $tbName 操作的數據表名
* @return int 受影響的行數
*/
public function delete($tbName) {
//安全考慮,阻止全表刪除
if (!trim($this-_where)) return false;
$sql = “delete from “.$tbName.” “.$this-_where;
$this-_clear = 1;
$this-_clear();
return $this-_doExec($sql);
}
/**
* 更新函數
* @param string $tbName 操作的數據表名
* @param array $data 參數數組
* @return int 受影響的行數
*/
public function update($tbName,array $data) {
//安全考慮,阻止全表更新
if (!trim($this-_where)) return false;
$data = $this-_dataFormat($tbName,$data);
if (!$data) return;
$valArr = ”;
foreach($data as $k=$v){
$valArr[] = $k.’=’.$v;
}
$valStr = implode(‘,’, $valArr);
$sql = “update “.trim($tbName).” set “.trim($valStr).” “.trim($this-_where);
return $this-_doExec($sql);
}
/**
* 查詢函數
* @param string $tbName 操作的數據表名
* @return array 結果集
*/
public function select($tbName=”) {
$sql = “select “.trim($this-_field).” from “.$tbName.” “.trim($this-_where).” “.trim($this-_order).” “.trim($this-_limit);
$this-_clear = 1;
$this-_clear();
return $this-_doQuery(trim($sql));
}
/**
* @param mixed $option 組合條件的二維數組,例:$option[‘field1′] = array(1,’=’,’or’)
* @return $this
*/
public function where($option) {
if ($this-_clear0) $this-_clear();
$this-_where = ‘ where ‘;
$logic = ‘and’;
if (is_string($option)) {
$this-_where .= $option;
}
elseif (is_array($option)) {
foreach($option as $k=$v) {
if (is_array($v)) {
$relative = isset($v[1]) ? $v[1] : ‘=’;
$logic = isset($v[2]) ? $v[2] : ‘and’;
$condition = ‘ (‘.$this-_addChar($k).’ ‘.$relative.’ ‘.$v[0].’) ‘;
}
else {
$logic = ‘and’;
$condition = ‘ (‘.$this-_addChar($k).’=’.$v.’) ‘;
}
$this-_where .= isset($mark) ? $logic.$condition : $condition;
$mark = 1;
}
}
return $this;
}
/**
* 設置排序
* @param mixed $option 排序條件數組 例:array(‘sort’=’desc’)
* @return $this
*/
public function order($option) {
if ($this-_clear0) $this-_clear();
$this-_order = ‘ order by ‘;
if (is_string($option)) {
$this-_order .= $option;
}
elseif (is_array($option)) {
foreach($option as $k=$v){
$order = $this-_addChar($k).’ ‘.$v;
$this-_order .= isset($mark) ? ‘,’.$order : $order;
$mark = 1;
}
}
return $this;
}
/**
* 設置查詢行數及頁數
* @param int $page pageSize不為空時為頁數,否則為行數
* @param int $pageSize 為空則函數設定取出行數,不為空則設定取出行數及頁數
* @return $this
*/
public function limit($page,$pageSize=null) {
if ($this-_clear0) $this-_clear();
if ($pageSize===null) {
$this-_limit = “limit “.$page;
}
else {
$pageval = intval( ($page – 1) * $pageSize);
$this-_limit = “limit “.$pageval.”,”.$pageSize;
}
return $this;
}
/**
* 設置查詢欄位
* @param mixed $field 欄位數組
* @return $this
*/
public function field($field){
if ($this-_clear0) $this-_clear();
if (is_string($field)) {
$field = explode(‘,’, $field);
}
$nField = array_map(array($this,’_addChar’), $field);
$this-_field = implode(‘,’, $nField);
return $this;
}
/**
* 清理標記函數
*/
protected function _clear() {
$this-_where = ”;
$this-_order = ”;
$this-_limit = ”;
$this-_field = ‘*’;
$this-_clear = 0;
}
/**
* 手動清理標記
* @return $this
*/
public function clearKey() {
$this-_clear();
return $this;
}
/**
* 啟動事務
* @return void
*/
public function startTrans() {
//數據rollback 支持
if ($this-_trans==0) self::$_dbh-beginTransaction();
$this-_trans++;
return;
}
/**
* 用於非自動提交狀態下面的查詢提交
* @return boolen
*/
public function commit() {
$result = true;
if ($this-_trans0) {
$result = self::$_dbh-commit();
$this-_trans = 0;
}
return $result;
}
/**
* 事務回滾
* @return boolen
*/
public function rollback() {
$result = true;
if ($this-_trans0) {
$result = self::$_dbh-rollback();
$this-_trans = 0;
}
return $result;
}
/**
* 關閉連接
* PHP 在腳本結束時會自動關閉連接。
*/
public function close() {
if (!is_null(self::$_dbh)) self::$_dbh = null;
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/193639.html