1. 程式人生 > 其它 >嵌入式程式設計

嵌入式程式設計

嵌入式程式設計

PyMySQL是一個純 Python 實現的 MySQL 客戶端操作庫,支援事務、儲存過程、批量執行等。

建立資料庫連線

db = pymysql.connect(host = 'localhost', user = 'root', password = '', db = 'test')

執行SQL語句

cursor = db.cursor() #建立遊標
sqlstr = """
INSERT INTO student VALUES ('2002','liming','2020-01-01','male')
"""
try:
    cursor.execute(sqlstr.lower())
    cursor.execute(
'select * from student;') results = cursor.fetchall() for row in results: print (row) except Exception as e: print ("Error: unable to fetch data", e)

為什麼要使用遊標?

  遊標是系統為使用者開闢的一個數據緩衝區,用來存放SQL語句產生的記錄,然後將產生的記錄逐條的賦值給主語句,交給主語句進行處理。

  1. SQL語句是面向集合的,執行一條SQL可能會產生多條記錄。
  2. 主語言是面向記錄的執行一條語句只能產生一條記錄。
  3. 如果只使用主變數的話,就不能將SQL產生的記錄通過主語言進行輸出。

關閉資料庫連線

db.commit()
db.close()

為什麼要使用db.commit()語句?

下面是官方給出的解釋:

This method sends aCOMMITstatement to the MySQL server, committing the current transaction. Since by default Connector/Python does not autocommit, it is important to call this method after every transaction that modifies data for tables that use transactional storage engines.

大概的意思是說:db.commit()會向MySQL伺服器傳送一個提交命令,提交當前的事務。使用Python嵌入式程式設計預設情況下並不會自動提交事務,如果資料表中的資料發生更改,對於事務儲存引擎(InnoDB)執行這一條語句是很有必要的。

如果不執行這一條語句那麼嵌入式程式設計對資料表所做的修改並不會更改資料庫中的資料。

習題

【表名和欄位】

–學生表

student(s_id,s_name,s_birth,s_sex) –學生編號,學生姓名, 出生年月,學生性別

–課程表

course(c_id,c_name,t_id) – –課程編號, 課程名稱, 教師編號

–成績表

score(s_id,c_id,s_score) –學生編號,課程編號,分數

使用嵌入式SQL對學生-課程資料庫完成下述功能:

1.插入一個新學生('2001','wangyan','2000-01-01','女')

import pymysql
db = pymysql.connect(host = 'localhost', user = 'root', password = '', db = 'test')
cursor = db.cursor()
sqlstr = """
INSERT INTO student VALUES ('2002','liming','2020-01-01','male')
"""
try:
    cursor.execute(sqlstr.lower())
    cursor.execute('select * from student;')
    results = cursor.fetchall()
    for row in results:
        print (row)
except Exception  as e:
    print ("Error: unable to fetch data", e)
db.commit()
db.close()

2.修改學號為‘2001’的學生姓名為'wangshan'

#include <iostream>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <stdio.h>
#pragma comment(lib, "libmysql.lib")
#include "C:\xampp\mysql\CPPConnector\include\mysql.h"

using namespace std;

MYSQL my_connect;

void mysql_connect() {
    mysql_init(&my_connect);//初始化
    if (mysql_real_connect(&my_connect, "localhost", "root", "", "test", 3306, NULL, 0)) {
        cout << "連線成功!" << endl;
    }
    else {
        cout << "連線失敗:" << mysql_error(&my_connect) << endl;
    }
}

void mysql_close() {
    mysql_close(&my_connect);
}

int main()
{
    mysql_connect();
    char sql[100] = "update student set s_name='wangshang' where s_id='2001'";
    mysql_query(&my_connect, sql);
    mysql_close();
    return 0;
}

3.用create語句建立新表s2(sno,sname,ssex,sbirth,sphone),欄位型別根據語義自行定義。

#include "jdbc/mysql_connection.h"
#include "jdbc/mysql_driver.h"
#include "jdbc/cppconn/statement.h"

#include <iostream>

using namespace std;

int main() {
    //初始化驅動
    try {
        sql::mysql::MySQL_Driver* driver = NULL;
        sql::Connection* con = NULL;
        sql::Statement* stmt;
        sql::ResultSet* res;
        driver = sql::mysql::get_mysql_driver_instance();
        if (driver == NULL)
        {
            cout << "driver is null" << endl;
        }
        con = driver->connect("tcp://localhost:3306/test", "root", "");
        if (con == NULL)
        {
            cout << "conn is null" << endl;
        }
        cout << "connect suceess" << endl;
        //con->setSchema("test");
        stmt = con->createStatement();
        stmt->executeQuery("create table s3 (sno varchar(20) primary key, sname varchar(20), ssex varchar(2), sbirth date, sphone varchar(20));");
        delete res;
        delete stmt;
        delete con;
    }
    catch (sql::SQLException &e) {
        cout << "# ERR: SQLException in " << __FILE__;
        cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
        cout << "# ERR: " << e.what();
        cout << " (MySQL error code: " << e.getErrorCode();
        cout << ", SQLState: " << e.getSQLState() << " )" << endl;
    }

    return 0;
}