Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Database \ Python MySQL database connection     - Ubuntu terminal command - see the port occupied and off (Linux)

- MySQL 5.6.26 source install (Database)

- Clojure programming languages: take full advantage of the Clojure plug-in Eclipse (Programming)

- Precautions against hackers Linux environment (Linux)

- Ubuntu installation module Python rq (Linux)

- Bad name two variables (Linux)

- Squid proxy server (Server)

- Log4Net (Linux)

- pkg-config to use (Linux)

- The first IOS Objective-C program (Programming)

- Android Application Development: Genymotion can not start solving (Linux)

- Ubuntu 15.10 installation and deployment Swift development environment (Linux)

- Linux find and xargs (Linux)

- After Ubuntu Password Forgot your way back (Linux)

- Linux installation skynet issue summary (Linux)

- The difference Docker save and export commands (Linux)

- Linux Powerful IDE - Geany configuration instructions (Linux)

- Ceph performance optimization summary (v0.94) (Server)

- To protect the temporary files for Linux security (Linux)

- 64-bit Windows Server 2012 R2 install Oracle 10g Second Edition (Database)

 
         
  Python MySQL database connection
     
  Add Date : 2018-11-21      
         
         
         
  Establish a database connection import MySQLdb
conn = MySQLdb.connect (host = "localhost", user = "root", passwd = "sa", db = "mytable")

More commonly used parameters include
host: the database server host name to connect, the default is the local host (localhost).

user: the database login name defaults to the current user.
passwd:. login secret database is empty by default.
db: name of the database you want to use with no default.
port:. MySQL service uses TCP port 3306 by default.
conn connection There are two important ways to add and modify commit [submit], rollback [withdraw] to add or modify

3, perform database operations
n = cursor.execute (sql, param)
We want to use the connection object to get a cursor object Next, we'll use the cursor to provide work.
These include two categories: 1 Run 2 receives the return value.
cursor method is used to execute commands:
callproc (self, procname, args): used to execute a stored procedure, the received parameters for the stored procedure name and parameter list, the return value is the number of affected rows
execute (self, query, args): parameter performs a single sql statement sql statement itself is received and a list of parameters used, the return value is the number of affected rows
executemany (self, query, args): execute sql statement singled out, but repeated the argument list of parameters executed, the return value is the number of affected rows
nextset (self): move to the next result set
cursor for receiving return values:
fetchall (self): return receive all the result rows.
fetchmany (self, size = None): receiver size bar return result rows if the value is greater than the size of the number of results returned rows of data will be returned cursor.arraysize.
fetchone (self): return a result rows.
scroll (self, value, mode = 'relative'):. Move the pointer to a row if mode = 'relative', it means that the current line move value item, if mode = 'absolute', said the first results from the set line of mobile value bars.
The following code is a complete example.
# Using sql statement, where parameters are to be received by% s placeholder is to be noted that, whether you want to insert the data of what type, the placeholder should always use% s
sql = "insert into cdinfo values ​​(% s,% s,% s,% s,% s)"
#param be tuple or list
param = (title, singer, imgurl, url, alpha)
# Execution, if successful, n value of 1
n = cursor.execute (sql, param)
# Again to perform a query operation
cursor.execute ( "select * from cdinfo")

# Fetchall we use this method. Thus, cds will be stored in all the results returned by the query. Each result is a tuple type of data that make up a tuple tuple
cds = cursor.fetchall ()

# Because it is tuple, so we can use this result set
print cds [0] [3]
# Or directly displayed, look at the real appearance of the result set
print cds

# If you need to bulk insert data, to do so
sql = "insert into cdinfo values ​​(0,% s,% s,% s,% s,% s)"
# Set each value is a tuple, the entire parameter set consisting of a tuple, or list
param = ((title, singer, imgurl, url, alpha), (title2, singer2, imgurl2, url2, alpha2))
# Use executemany way to bulk insert data. This is a really cool way!
n = cursor.executemany (sql, param)

Note that (or that I am surprised) completes execution after the insertion or deletion or modification, you need to call about conn.commit () method to commit. Thus, the data will actually stored in the database. I unclear whether my mysql setup problems, in short, today I used at the beginning, if you do not commit, that data is not retained in the database, but the data in the database actually spent because automatic numbering has been accumulated and the number of rows affected is not returned to zero.

4, close the database connection
Close pointer need separate objects and connection objects. They have the same name method
cursor.close ()
conn.close ()

5 Coding (prevent distortion)

Note that point:

1 Python settings file encoding utf-8 (in front of the file plus # encoding = utf-8)
    2 MySQL database charset = utf-8
    3 Python MySQL connection is to add parameters charset = utf8
    4 Set Python's default encoding is utf-8 (sys.setdefaultencoding (utf-8)


# Encoding = utf-8

import sys

import MySQLdb

reload (sys)

sys.setdefaultencoding ( 'utf-8')

db = MySQLdb.connect (user = 'root', charset = 'utf8')
 

Note: MySQL configuration file settings must also be configured to utf8

 

6. The module Demo

[Root @ localhost python] # more mysql.py
#! / Usr / bin / python


import module import MySQLdb ###
conn = MySQLdb.connect (user = "root", passwd = "ESBecs00! @ #", db = "test") ### connected to mysql
cursor = conn.cursor () ### a link cursor


sql = "select * from test" ### sql statement
n = cursor.execute (sql) ### execute sql
print n ### is executed successfully returns n (n represents the number of impacts, which is 3)

row = cursor.fetchall () ### fetchall () Returns all live results, fetchone () returns a live result
print row ### to print out the return results


print "################################################ #########Dividing line####################################### ########### "


cursor.execute ( '' '### can also be placed directly inside the sql statement execution
create table if not exists food (
id int (10) primary key,
name varchar (20),
age int (10)
)
'' ')
sql = "desc food"
cursor.execute (sql)
row = cursor.fetchall ()
print row

 

cursor.close () ### Close the cursor
conn.close () ### closes the connection

 


Results of the

[Root @ localhost python] # python mysql.py
3
(( 'Zhangsan',), ( 'lisi',), ( 'wangwu',))
################################################## #######
mysql.py:21: Warning: Table 'food' already exists
  '' ')
(( 'Id', 'int (10)', 'NO', 'PRI', None, ''), ( 'name', 'varchar (20)', 'YES', '', None, '' ), ( 'age', 'int (10)', 'YES', '', None, '')
 

 

Execute the following SQL statement to capture the return value:
// Get the cursor connection
cursor = conn.cursor ()
//Inquire
sql = "select * from [table]."
cursor.execute (sql)

return value
cur.execute ( 'select * from tables')
Returns the number of rows to get the value of SQL statements, such as: 2L, represents a row.
Then, line information can be obtained from fetchone or fetchall method of that object.

Get line information
fetchone object pointer () method, is to give each row tuple return value:
Quote
>>> Row = cur.fetchone ()
>>> Print row
( 'User1', '52c69e3a57331081823331c4e69d3f2e', 1000L, 1000L, '/ home / FTP / user1', '')

fetchall object pointer () method, you can remove all rows in the result set pointer, the result set returns a tuple (tuples):
Quote
>>> Cur.scroll (0, 'absolute')
>>> Row = cur.fetchall ()
>>> Print row
(( 'User1', '52c69e3a57331081823331c4e69d3f2e', 1000L, 1000L, '/ home / FTP / user1', ''), ( 'user2', '7e58d63b60197ceb55a1c487989a3720', 1000L, 1000L, '/ home / FTP / user2', None ))

Move the pointer
When fetchone () method, the pointer is moved occur. So, if not reset the pointer, use fetchall information will only contain the line pointer back.
Manually move the pointers:
cur.scroll (int, parm)
Meaning:
Quote
int: The number of lines is an integer; in relative mode, positive move downwards, negative values ​​indicate movement upward.
parm: moving mode, the default is relative, relative mode; acceptable absoulte, absolute mode.

Modify data
Modify data, including insert, update, delete. They are using a pointer object execute () method is executed:
cur.execute ( "insert into table (row1, row2) values ​​( '111', '222')")
cur.execute ( "update table set row1 = 'test' where row2 = 'row2'")
cur.execute ( "delete from table where row1 = 'row1'")

Because single quote " '" is used to identify the SQL statement, therefore, python string need to use double quotes.
Alternatively, you can use the python "format string" writing, simplified command, for example:
cur.execute ( "update table set row1 = '% s' where row2 = '% s'"% ( 'value1', 'value2'))

Please note that, '% s' single quotation marks are spaced characters SQL statements, 'value1' single quotation marks are python string break character, its meaning is different. Need break character, and use double quotes or single quotes as a spacer, to be determined according to its meaning. For example, there are:
cur.execute ( "update FTPUSERS set passwd =% s where userid = '% s'"% ( "md5 ( '123')", 'user2'))
Here, paswd =% s is due to SQL's md5 () function does not require single quotes interval; "md5 ( '123')" is a string containing a python in single quotes, double quotes around it.

Submit modification
Under normal circumstances, MySQLdb module automatically commit changes. But after we update data manually run again:
conn.commit ()

Close the database connection
Close pointer need separate objects and connection objects. They have the same name method
cursor.close ()
conn.close ()
     
         
         
         
  More:      
 
- Ubuntu set Swap Space Tutorial (Linux)
- Oracle for Oracle GoldenGate to achieve a one-way synchronization DDL operations (Database)
- Wi-Fi hackers use to attack your seven methods (Linux)
- Source MongoDB 3.2.1 installed on CentOS6.5 (Database)
- Linux system Passwd file detailed analysis (Linux)
- CentOS7 + Redis Live Installation and Configuration (Linux)
- Ubuntu upgrade to Linux Kernel 4.2.3 Kernel (Linux)
- Java object initialization (Programming)
- FFmpeg compiled with only H264 decoding library (Programming)
- Ubuntu 14.04 to install file editor KKEdit 0.1.5 version (Linux)
- Linux kernel network subsystem analysis (Programming)
- The array of C language (Programming)
- AngularJS achieve picture upload feature (Programming)
- CentOS 6.0 system security level (Linux)
- 11 you Linux Terminal Command (Linux)
- Download Google Android source code under Ubuntu 4.4 (Linux)
- Sublime Text 3 best features, plug-ins and settings (Linux)
- Spark read more HBase tables a RDD (Server)
- Oracle 11g logical standby achieve BI needs (Database)
- Java to achieve local fileCopy (Programming)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.