Installing MySQL for Python 3

sudo apt-get install build-essential python3-dev libmysqlclient-dev

sudo apt-get install python3-pip

**install the MySQL connector
using pip:**

sudo pip3 install mysql-connector

or

sudo apt-get install python3-mysql.connector

demo_mysql_connection.py:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword"
)

print(mydb)

Creating a Database
To create a database in MySQL, use the "CREATE DATABASE" statement:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE mydatabase")

Creating a Table

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")

Insert Into Table

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.")

Select From a Table

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM customers")

myresult = mycursor.fetchall()

for x in myresult:
  print(x)

Python 使用 MySQLdb
檢查是否有安裝 MySQLdb 模組

python -c "import MySQLdb"

ImportError: No module named MySQLdb

MySQLdb 只支持python2,不支持python3

python mysql db 全局变量

global conn 
conn = mysql.connector.connect(
      host="localhost",
      user="yourusername",
      password="yourpassword"
    )

python html parse

from html.parser import HTMLParser


class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Encountered a start tag:", tag, type(tag))
        for attr in attrs:
            # print("     attr:", attr, type(attr))
            if(tag == "a" and attr[0] == 'href'):
                print("href = ", attr[1])


    def handle_endtag(self, tag):
        print("Encountered an end tag :", tag)

    def handle_data(self, data):
        print("Encountered some data  :", data)


parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
            '<body><h1>Parse me!</h1><a href="https://www.baidu.com/">baidu</a></body></html>')

python file read

    try:
        f = open(filebat)
    except FileNotFoundError:
        print("file not found :", filebat)
    else:
        strfile = f.read()

python bytes to string

>>> b"abcde"
b'abcde'

# utf-8 is used here because it is a very common encoding, but you
# need to use the encoding your data is actually in.
>>> b"abcde".decode("utf-8") 
'abcde'

python encoding

import os
import sys

ch = '中国'

print('GBK:', ch.encode('gbk'))
print('UTF8:', ch.encode('utf8'))

print('GBK:', ch.encode('gbk').decode('gbk'))
print('UTF8:', ch.encode('utf8').decode('utf8'))

GBK: b'xd6xd0xb9xfa'
UTF8: b'xe4xb8xadxe5x9bxbd'
GBK: 中国
UTF8: 中国

python tcp socket

import socket

socket.setdefaulttimeout(2)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.connect(("127.0.0.1", 5000))
except Exception as e:
    print( str(e))
    exit(0)

s.send(b'GET / HTTP/1.1\r\n\r\n')
while True:
    data = s.recv(1024)
    if data:
        print(data.decode("utf8"))
    else:
        break

输出:

HTTP/1.0 200 OK

Content-Type: text/html; charset=utf-8
Content-Length: 10
Server: Werkzeug/2.0.3 Python/3.8.10
Date: Wed, 09 Mar 2022 01:46:40 GMT


Index Page

安装bluetooth

sudo apt-get update
sudo apt-get install python-pip python-dev ipython

sudo apt-get install bluetooth libbluetooth-dev
sudo pip install pybluez

python3 requests post octet-stream

import requests
with open('./x.png', 'rb') as f:
    data = f.read()
res = requests.post(url='http://httpbin.org/post',
                    data=data,
                    headers={'Content-Type': 'application/octet-stream'})

python 实现sm3计算hash

p1 = subprocess.Popen(["echo",  "-n", str], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["openssl", "dgst", "-sm3"], stdin=p1.stdout, stdout=subprocess.PIPE)
sm3 = p2.stdout.readline()[9:-1]
print('sm3 = ', sm3)

python hex string to string

a = 'aabbccddeeff'
a_bytes = bytes.fromhex(a)
print(a_bytes)
b'\xaa\xbb\xcc\xdd\xee\xff'
aa = a_bytes.hex()
print(aa)
aabbccddeeff

python3 read file line by line

file1 = open('myfile.txt', 'r')
Lines = file1.readlines()
 
count = 0
for line in Lines:
    count += 1
    print("Line{}: {}".format(count, line.strip()))

python3 ubuntu beep

import os
import time
duration = 1  # seconds
freq = 440  # Hz

bool1 = True
elapsed_time = 0
while bool1:
    start = time.time()
    elapsed_time += time.time() - start
    if elapsed_time >= 2.5:#Adjust yourself
        os.system('play -nq -t alsa synth {} sine {}'.format(duration, freq))
        bool1 = False
本文链接地址:https://const.net.cn/661.html

标签: python

添加新评论