Python operation mysql steps

The process first creates the connection connet() creates the cursor cursor() executes the SQL statement and finally closes the connection and cursor, first closes the cursor, and then closes the link

# 创建连接
conn = connect(host="localhost",port=3306,database="jing_dong",user="root",password="mysql",charset=utf8)
# 创建游标
cs1 = conn.cursor()
sql = "select * from goods;"
cs1.execute(sql)

content = cs1.fetchone()
print(content)

cs1.close()
conn.close()

Take out one or more or all data fetchone() a fetchmany(3) take out three fetchall() take out all

-- foreign key

  • How to prevent the insertion of invalid information, that is, to determine whether the type or brand name exists before inserting? Foreign keys can be used to solve the problem
  • Foreign key constraints: verify the validity of the data
  • Keywords: foreign key, only the innodb database engine supports foreign key constraints

How to cancel foreign key constraints

  • You need to get the foreign key constraint name first, the name will be automatically generated by the system, you can get the name show create table goods by viewing the table creation statement;
  • After getting the name, you can delete the foreign key constraint according to the name alter table goods drop foreign key foreign key name

--sql injection

  • Parameterization of SQL statements can effectively prevent SQL injection
  • Note: This is different from python's string formatting, all use %s placeholders
  • sql = "select * from goods where name = %s"
  • self.cs1.execute(sql,[name])

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325391909&siteId=291194637