在命令行输入pip install mysql-connector-python
import mysql.connector try: config={ 'host':'127.0.0.1', # MySQL服务器IP地址,'127.0.0.1'为localhost 'port':3306, # 默认 'user':'root', # 数据库用户名 'password':'123123',# 数据库密码 'database':'s-t', # 数据库名称 'charset':'utf8' # 默认 } con=mysql.connector.connect(**config) ### 要进行的操作 ### ################## # print(con.connection_id) con.close() except mysql.connector.Error as e: print(e)
try: config={ 'host':'127.0.0.1', 'port':3306, 'user':'root', 'password':'123123', 'database':'s-t', 'charset':'utf8' } con=mysql.connector.connect(**config) ### 要进行的操作 ### cursor=con.cursor() sql=("insert into `s-t`.student values('505','小红','女','1976-6-24','34566')") # SQL语句 cursor.execute(sql) con.commit() # print(cursor.lastrowid) cursor.close() ################## con.close() except mysql.connector.Error as e: print(e)
try: config={ 'host':'127.0.0.1', 'port':3306, 'user':'root', 'password':'123123', 'database':'s-t', 'charset':'utf8' } con=mysql.connector.connect(**config) ### 要进行的操作 ### cursor=con.cursor(dictionary=True) # True以字典形式返回结果,False以元组形式返回结果 sql=("select * from `s-t`.student") cursor.execute(sql) result=cursor.fetchall() #result即为取出的数据 cursor.close() ################## con.close() except mysql.connector.Error as e: print(e)