Mysql 数据库操作 - C/C++转Python边用边学(一)

本文介绍了从C/C++背景转向Python进行MySQL数据库操作的过程,涵盖了数据库的连接、创建、插入、查询和删除等基本操作。通过学习,读者将了解如何在Python中使用相关库进行数据库交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引言

    Python版本:2.7.12
    开发IDE:Pycharm
    数据库:Mysql
    涉及非系统库: MySQLdb
    目的:实现数据库的增删改查

涉及知识简介

    主要介绍一些常规的语法内容,以C/C++为对比例子进行介绍。

注释

注释 # 相当于 //
注释 """ 相当于 /*
再注释 """ 相当于 */

库(头文件)

/*  C++包含头文件  */
#include <iostream>
"""  Python 包含头文件  """
import os

函数

# 函数声明的基本格式
"""  
Python Code:
def关键字 函数名 (参数1,参数2,...,参数N):
    return 参数
"""
# 返回值类型自动识别
def function(_name):
    return _name 
/*  
// C++ Code: 
*/
std::string function(std::string _name) {
    return _name;
}  

循环

# Python Code
# 元组声明
data = [(1,2),(3,4)]
# 双层循环
for row in data:
    for r in row:
        print(r)

/*  C++ Code  */
int main(void) {
    int data[2][2] = { { 1, 2 }, {3, 4} };
    for (int row = 0; row < 2; ++row) {
        for (int r = 0; r < 2; ++r) {
            std::cout << data[row][r];
        }
    }
    system("pause");
}

打印函数

# Python Code
data = 2
print(u"变量data: %d" % data)
/*  C++ Code  */
int data = 2;
std::wcout << "变量data: " << data << std::endl;




Mysql 数据库操作

     讲解利用 Python 脚本,对 Mysql 数据库进行增删改查

连接与断开

#coding=utf-8

import MySQLdb


temp_mysql = MySQLdb.connect(host = "localhost", user = "root", passwd = "123456", db = "test", charset = "utf8")

print (temp_mysql)
temp_mysql.close()
print (temp_mysql)

输出结果
<_mysql.connection open to 'localhost' at 393db38>
<_mysql.connection closed at 393db38>

创建

#coding=utf-8

# 导入Mysql库
import MySQLdb

# 获得Mysql连接实例
temp_mysql = MySQLdb.connect(host = "localhost", user = "root", passwd = "123456", db = "test", charset = "utf8")
#获得可以操作的实例游标
mysql_cursor = temp_mysql.cursor()
# 初始化 sql 语句 创建表前检测当前表是否存在,存在则删除。
sql="DROP TABLE IF EXISTS `webmap_crnt`; \
    CREATE TABLE `webmap_crnt` ( \
    `car_id` varchar(31) NOT NULL, \
    `longitude` varchar(15) NOT NULL, \
    `latitude` varchar(15) NOT NULL, \
    `updt_tm` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP \
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"

result = mysql_cursor.execute(sql)
print(u"执行结果: %d" % result)

print (temp_mysql)
# 注释此条关闭实例语句,则清除了警告
temp_mysql.close()
print (temp_mysql)

执行上述过程的时候会发现有一条警告信息
Exception _mysql_exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query') in <bound method Cursor.__del__ of <MySQLdb.cursors.Cursor object at 0x0000000003A3E0B8>> ignored

# 注释此条关闭实例语句,则清除了警告
temp_mysql.close()
查看表是成功创建的,则说明在Python中创建表的函数,并不是同步进行的,以至于他会警告你,这样做具有一定的危险性,有时会出现不可预料的结果。


新增

有基础的朋友看了上面的函数应该能够清晰明了,python的调用过程了,并能举一反三得知新增的执行状态。
#coding=utf-8

# 导入Mysql库
import MySQLdb

# 获得Mysql连接实例
temp_mysql = MySQLdb.connect(host = "localhost", user = "root", passwd = "123456", db = "test", charset = "utf8")
mysql_cursor = temp_mysql.cursor()

sql="INSERT INTO `test`.`webmap_crnt` (`car_id`, `longitude`, `latitude`) VALUES ('1', '1', '1');"

result = mysql_cursor.execute(sql)
print(u"执行结果: %d" % result)
# 不进行提交则执行无效
temp_mysql.commit()

print (temp_mysql)
temp_mysql.close()
print (temp_mysql)


查询

#coding=utf-8

# 导入Mysql库
import MySQLdb

# 获得Mysql连接实例
temp_mysql = MySQLdb.connect(host = "localhost", user = "root", passwd = "123456", db = "test", charset = "utf8")
mysql_cursor = temp_mysql.cursor()

sql = "SELECT * FROM webmap_crnt;"
result = mysql_cursor.execute(sql)
print(u"返回元组的数量: %d" % result)

for row in mysql_cursor:
    for r in row:
        print(r)

print (temp_mysql)
temp_mysql.close()
print (temp_mysql)

删除

#coding=utf-8

# 导入Mysql库
import MySQLdb

# 获得Mysql连接实例
temp_mysql = MySQLdb.connect(host = "localhost", user = "root", passwd = "123456", db = "test", charset = "utf8")
mysql_cursor = temp_mysql.cursor()

sql="DELETE FROM `webmap_crnt`;"
result = mysql_cursor.execute(sql)
# 不进行提交则执行无效
temp_mysql.commit()

print(u"执行结果: %d" % result)
print (temp_mysql)
temp_mysql.close()
print (temp_mysql)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值