Learn how to use MySQL in Python

Source: Internet
Author: User
Tags mysql in rowcount

First encountered a lot of problems in the Pycharm import MySQL, mysqldb no use, and finally looked up some information, found in python3.x has been changed to pip install Mysqlclient

And then import mysqldb on it.

After the connection to the database can do some simple additions and deletions to change the operation

Note: Add or delete code is best added try. Exception. Finally to check

Import MySQLdb
Conn=mysqldb.connect (host= ' 127.0.0.1 ', port=3306,user= ' root ', passwd= ' Fanxiaoqian ', db= ' test ', charset= ' UTF8 ')

Cursor=conn.cursor ()

Cursor.execute ("'
CREATE table if not EXISTS user
(
UserID bigint (one) PRIMARY KEY,
Username VARCHAR (20)
)

‘‘‘)
For I in range (10):
Cursor.execute ("INSERT into User (Userid,username) values ('%d ', '%s ')"% (int (i), ' name ' +str (i)))

Conn.commit ()
# Res=cursor.fetchall ()
# for row in res:
# print (ROW)
#
# sql= ' select * from user '
# cursor.execute (SQL)
# Print (Cursor.rowcount)
#
# rs = Cursor.fetchone ()
# Print (RS)
#
# rs = Cursor.fetchmany (3)
# Print (RS)
# Rs=cursor.fetchall ()
# Print (RS)

Sql_insert = ' INSERT INTO user (Userid,username) VALUES ("Name10") '
sql_update = ' Update user set username= ' name91 ' where userid=9 '
Sql_delete = ' Delete from user where userid=3 '

Cursor.execute (Sql_insert)
Print (Cursor.rowcount)
Cursor.execute (Sql_update)
Print (Cursor.rowcount)
Cursor.execute (Sql_delete)
Print (Cursor.rowcount)


Conn.commit ()

Reference Blog: https://www.cnblogs.com/itdyb/p/5700614.html

Learn how to use MySQL in Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.