The method steps of pycharm accessing MySQL database

Time:2019-12-1

You don’t need to add a driver package like eclipse, just download a pymysql package in pycharm.

Then link to MySQL of your computer and visit it.

Source code is as follows

import pymysql

 

#Establish database connection

conn = pymysql.Connect(

  host='localhost',

  port=3306,

  User = 'user',

  Passwd = 'password',

  DB = 'database',

  charset='utf8'

)

 

#Get cursor

cursor = conn.cursor()

# print(conn)

# print(cursor)

 

#1. Query from the database

# sql="INSERT INTO userinfor(user_name,pass_word)"

sql = "SELECT * FROM userinfor"

#Cursor executes SQL statement

cursor.execute(sql)

#Number of print execution results

print(cursor.rowcount)

 

#There are three pieces of data in the result of traversal with fetch method

 

#Rs = cursor. Fetchone() -- put the first result in RS

#Re = cursor.fetchmany (3)

RR = cursor. Fetchall() -- put all results in RR

#Process results

for row in rr:

  Print ("ID is: =% s, name is: =% s, password is: =% s"% row)

#Print (RE) outputs two pieces of data, because the fetch () method is based on the last fetch () method

 

 

#2 insert data into database

Sql_insert = "insert into userinfo (username, password) values ('zte ',' 123 ')"

#Execute statement

cursor.execute(sql_insert)

#Transaction commit, otherwise the database will not be updated

conn.commit()

print(cursor.rowcount)

 

#Modify content in the database

sql_update = "UPDATE userinfor SET username='121' WHERE id=21"

cursor.execute(sql_update)

conn.commit()

 

#Delete the contents of the database and use try catch statement to rollback the transaction

try:

  sql_delete = "DELETE FROM userinfor WHERE id=6"

  cursor.execute(sql_delete)

  conn.commit()

except Exception as e:

  print(e)

  #Transaction rollback, that is, after an error occurs, it will not continue to execute, but will return to the state that the program has not been executed, and the original execution will not be counted

  conn.rollback()

 

#Database connection and cursor closing

conn.close()

cursor.close()

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.

Recommended Today

Manjaro uses SS method (requires nodejs environment)

Just installed manjaro, need to installshadowsocks-qt5+Proxy SwitchyOmega, but the latest Chrome has long blocked the installation of non Google store CRX channels. Here is my solution, which is troublesome but usable. If you are familiar with NPM commands in nodejs, you won’t find it troublesome, because nodejs is used for compilation. Preparation environment: A VPS […]