Python to operate MySQL database specific methods

  • 2020-04-02 13:03:53
  • OfStack


import MySQLdb

try:
    conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',port=3306)
    cur=conn.cursor()
    cur.execute('select * from user')
    cur.close()
    conn.close()
except MySQLdb.Error,e:
     print "Mysql Error %d: %s" % (e.args[0], e.args[1]) 

Please note to change your database, host name, user name, and password.

Here is a general example of inserting data, batch inserting data, and updating data:


import MySQLdb

try:
    conn=MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306)
    cur=conn.cursor()

    cur.execute('create database if not exists python')
    conn.select_db('python')
    cur.execute('create table test(id int,info varchar(20))')

    value=[1,'hi rollen']
    cur.execute('insert into test values(%s,%s)',value)

    values=[]
    for i in range(20):
        values.append((i,'hi rollen'+str(i)))

    cur.executemany('insert into test values(%s,%s)',values)

    cur.execute('update test set info="I am rollen" where id=3')

    conn.commit()
    cur.close()
    conn.close()

except MySQLdb.Error,e:
     print "Mysql Error %d: %s" % (e.args[0], e.args[1]) 

Note that you must have the conn.com MIT () clause to commit transactions, otherwise you cannot actually insert data.

After running my MySQL database, the results are not shown in the figure above.


import MySQLdb

try:
    conn=MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306)
    cur=conn.cursor()

    conn.select_db('python')

    count=cur.execute('select * from test')
    print 'there has %s rows record' % count

    result=cur.fetchone()
    print result
    print 'ID: %s info %s' % result

    results=cur.fetchmany(5)
    for r in results:
        print r

    print '=='*10
    cur.scroll(0,mode='absolute')

    results=cur.fetchall()
    for r in results:
        print r[1]

 
    conn.commit()
    cur.close()
    conn.close()

except MySQLdb.Error,e:
     print "Mysql Error %d: %s" % (e.args[0], e.args[1]) 

I'm not going to stick it. It's too long.

Query after the Chinese will be displayed correctly, but in the database is garbled. After I looked it up on the Internet, I found that using a property can be done:

In the Python code

Conn = mysqldb.connect (host='localhost', user='root', passwd='root', db='python') with an attribute:
  To:
Conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python',charset='utf8')
Charset is to be the same as your database code, if the database is gb2312, write charset='gb2312'.

Here are some common functions:

Then, this connection object also provides support for transaction operations, the standard method
Commit ()
Rollback () rolled back

Methods used to execute commands with cursor:
Callproc (self, procname, args): used to execute the stored procedure. The parameters received are the stored procedure name and parameter list, and the return value is the number of affected rows
Execute (self, query, args): executes a single SQL statement, takes the parameters of the SQL statement itself and the list of parameters used, and returns the number of affected rows
Executemany (self, query, args): executes the one-on-one hit SQL statement, but repeats the arguments in the argument list, returning the number of affected rows
Nextset (self): moves to the next result set

Method used to receive return values with cursor:
Fetchall (self): receives all returned rows.
Fetchmany (self, size=None): receives a size bar to return a result row. If the value of size is greater than the number of result rows returned, the cursor. Arraysize bar data is returned.
Fetchone (self): returns a result row.
Scroll (self, value, mode='relative'): moves the pointer to a row. If mode='relative', moves the value bar from the current row, and if mode='absolute', moves the value bar from the first row of the result set.


Related articles: