Python2.7 with MySQL Connector/Python Sample(Windows OS)

Install the MySQL Connector

Install package

Double click the package and click the Run button to complete installation.

Test if installed successfully

Open windows command line

py
>>> import mysql.connector

If there is no error then it is successful.

Code with example

import mysql.connector
from mysql.connector import errorcode
database = 'testpython'

def get_db_connectoin(database):
    username = 'root'
    password = '******'
    hostname = 'localhost'
    port = 3306
    database = database
    connection = None 
    try:
        connection = mysql.connector.connect(user=username, password=password, host=hostname, port=port, database=database)
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            print 'Username,Password Error'
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            print 'Database does not exist'
            connection = mysql.connector.connect(user=username, password=password, host=hostname, port=port)
            cursor = connection.cursor()
            cursor.execute("CREATE DATABASE "+ database + " DEFAULT CHARACTER SET 'utf8'")
        else:
            print err
    else:
        connection.database = database
    return connection

def create_table(connection, sql):
    cursor = connection.cursor()
    try:
        cursor.execute(sql)
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
            print "Table already exist"
        else:
            print err
    else:
        cursor.close()
        connection.close()
    return

def inset_data(connection, sql, args):
    cursor = connection.cursor()
    try:
        cursor.execute(sql, args)
        connection.commit()
    except mysql.connector.Error as err:
        print err
    else:
        cursor.close()
        connection.close()
    return

def query_data(connection, sql, args):
    cursor = connection.cursor()
    cursor.execute(sql, args)
    return cursor

connection = get_db_connectoin(database)
createSql = ("CREATE TABLE `TEST_TABLE` ("
             "`ID` INT(11) PRIMARY KEY AUTO_INCREMENT,"
             "`NAME` VARCHAR(64) NOT NULL,"
             "`AGE` INT(3))"
            )
create_table(connection=connection, sql=createSql)

connection = get_db_connectoin(database)
insetSql = "INSERT INTO TEST_TABLE(NAME,AGE) VALUES (%(NAME)s,%(AGE)s)" 
args = {'NAME':'jason','AGE':28}
inset_data(connection=connection, sql=insetSql, args=args)

connection = get_db_connectoin(database)
querySql = "SELECT * FROM TEST_TABLE WHERE NAME=%s AND AGE > %s"
args = ("jason", 26)
cursor = query_data(connection=connection, sql=querySql, args=args)
for (id, name, age) in cursor:
    print id
    print name
    print age
    print '\n'
cursor.close()
connection.close()

References:

当然可以!以下是一个简单的Python+MySQL学生管理系统实例。 首先,你需要安装MySQLPythonMySQL连接器。你可以使用以下命令在Ubuntu上安装: ``` sudo apt-get install mysql-server pip install mysql-connector-python ``` 接下来,创建一个名为“students”的数据库,并在其中创建一个名为“student_info”的表。以下是表的结构: ```sql CREATE TABLE student_info ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT, gender VARCHAR(10), major VARCHAR(255) ); ``` 接下来,你可以使用以下Python代码连接到数据库,并添加、删除、更新和查询学生信息。 ```python import mysql.connector # Connect to the database db = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="students" ) # Add a new student def add_student(name, age, gender, major): cursor = db.cursor() sql = "INSERT INTO student_info (name, age, gender, major) VALUES (%s, %s, %s, %s)" values = (name, age, gender, major) cursor.execute(sql, values) db.commit() print(cursor.rowcount, "record inserted.") # Delete a student by ID def delete_student(id): cursor = db.cursor() sql = "DELETE FROM student_info WHERE id = %s" value = (id,) cursor.execute(sql, value) db.commit() print(cursor.rowcount, "record(s) deleted.") # Update a student by ID def update_student(id, name, age, gender, major): cursor = db.cursor() sql = "UPDATE student_info SET name = %s, age = %s, gender = %s, major = %s WHERE id = %s" values = (name, age, gender, major, id) cursor.execute(sql, values) db.commit() print(cursor.rowcount, "record(s) updated.") # Get all students def get_students(): cursor = db.cursor() cursor.execute("SELECT * FROM student_info") rows = cursor.fetchall() for row in rows: print(row) # Get a student by ID def get_student(id): cursor = db.cursor() sql = "SELECT * FROM student_info WHERE id = %s" value = (id,) cursor.execute(sql, value) row = cursor.fetchone() if row: print(row) else: print("No record found.") # Add a few sample students add_student("John Doe", 20, "Male", "Computer Science") add_student("Jane Smith", 22, "Female", "Business") add_student("Bob Johnson", 19, "Male", "Engineering") # Get all students get_students() # Update a student update_student(2, "Jane Doe", 23, "Female", "Marketing") # Get a student by ID get_student(1) # Delete a student delete_student(3) # Get all students again get_students() ``` 这只是一个简单的示例,你可以根据自己的需要进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值