You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在MySQL存储查询十六进制值及树莓派热敏打印机ID读取技术咨询

Hey there! Let's break down your two technical questions with practical, actionable solutions:

1. 如何在MySQL数据库中存储和查询十六进制值

MySQL offers flexible ways to handle hex values, depending on whether you need human-readable storage or efficient binary storage:

存储十六进制值

  • Option 1: Store as string (VARCHAR/CHAR)
    If you just need to view hex values directly, save them as plain strings (like 'A1B2' or '0xA1B2') in a VARCHAR column. No conversion needed for insertion:
    CREATE TABLE hex_samples (id INT, hex_str VARCHAR(20));
    INSERT INTO hex_samples VALUES (1, 'A1B2'), (2, '0xC3D4');
    
  • Option 2: Store as binary data (BINARY/VARBINARY)
    For space efficiency or direct binary operations, use the UNHEX() function to convert hex strings to binary before storing:
    CREATE TABLE binary_samples (id INT, hex_bin VARBINARY(10));
    INSERT INTO binary_samples VALUES (1, UNHEX('A1B2')), (2, UNHEX('C3D4'));
    

查询十六进制值

  • Query string-stored hex values
    Fetch directly, or use UNHEX() to convert to binary (strip the 0x prefix first if present):
    -- Get the raw string
    SELECT hex_str FROM hex_samples WHERE id = 1;
    -- Convert string to binary
    SELECT UNHEX(REPLACE(hex_str, '0x', '')) FROM hex_samples WHERE id = 2;
    
  • Query binary-stored hex values
    Use HEX() to convert binary data back to a human-readable hex string:
    SELECT HEX(hex_bin) FROM binary_samples WHERE id = 1;
    
2. 树莓派连接热敏打印机:从MySQL读取Vendor ID和Product ID

Looking at your code snippet, the key issue is that the IDs pulled from your VARCHAR column are strings, but the escpos.printer.Usb class requires integer values. Plus, you'll need to fix USB permissions on the Pi. Here's the corrected approach:

Step 1: Fix the code to convert ID types

Assuming your database stores IDs as hex strings (e.g., '0x0483') or decimal strings (e.g., '1155'), convert them to integers before initializing the printer:

import MySQLdb
from escpos.printer import Usb

# Replace with your actual database credentials
HOST = 'localhost'
PORT = 3306
USER = 'your_username'
PASSWORD = 'your_password'
database = 'your_db'

try:
    # Connect to database and fetch printer details
    db = MySQLdb.connect(host=HOST, port=PORT, user=USER, passwd=PASSWORD, db=database)
    cursor = db.cursor()
    cursor.execute("SELECT * FROM printerdetails")
    result = cursor.fetchall()
    db.close()

    for row in result:
        # Convert string IDs to integers
        # Use this if IDs are stored as hex strings (with or without 0x prefix)
        printer_vendor_id = int(row[2], 16)
        printer_product_id = int(row[3], 16)
        
        # Use this instead if IDs are stored as decimal strings
        # printer_vendor_id = int(row[2])
        # printer_product_id = int(row[3])

        # Initialize printer (adjust interface/in_ep/out_ep based on your printer model)
        try:
            printer = Usb(printer_vendor_id, printer_product_id, interface=0, in_ep=0x82, out_ep=0x01)
            # Test print
            printer.text("Hello from your Raspberry Pi!\n")
            printer.cut()
            printer.close()
            print("Print job successful!")
        except Exception as e:
            print(f"Failed to initialize printer: {str(e)}")
except Exception as e:
    print(f"Database error: {str(e)}")

Step 2: Fix Raspberry Pi USB permissions

By default, regular users can't access USB devices on the Pi, which will cause a Permission denied error. Fix this with a udev rule:

  1. Run lsusb to find your printer's details (e.g., Bus 001 Device 004: ID 0483:5750 STMicroelectronics where 0483 is the vendor ID and 5750 is the product ID).
  2. Create a udev rule file:
    sudo nano /etc/udev/rules.d/99-thermal-printer.rules
    
  3. Add this line (replace with your printer's vendor and product IDs):
    SUBSYSTEM=="usb", ATTRS{idVendor}=="0483", ATTRS{idProduct}=="5750", MODE="0666"
    
  4. Reload udev rules:
    sudo udevadm control --reload-rules && sudo udevadm trigger
    

内容的提问来源于stack exchange,提问作者Akash Nil

火山引擎 最新活动