PyMySQL

1、安装

[root@localhost ~]# pip install PyMySQL

 

2、初识

创建数据表结构:

mysql> CREATE TABLE `users` (
    ->     `id` int(11) NOT NULL AUTO_INCREMENT,
    ->     `email` varchar(255) COLLATE utf8_bin NOT NULL,
    ->     `password` varchar(255) COLLATE utf8_bin NOT NULL,
    ->     PRIMARY KEY (`id`)
    -> ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
    -> AUTO_INCREMENT=1 ;
Query OK, 0 rows affected (0.07 sec)

使用示例:

import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='192.168.1.134',
                             port=3306,
                             user='remote',
                             password='tx_1234abc',
                             db='Jefrey',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:   #增加
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))

    # connection is not autocommit by default. So you must commit to save your changes.
    connection.commit()   # 提交,不然数据库不生效

    with connection.cursor() as cursor:   #查询
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('webmaster@python.org',))
        result = cursor.fetchone()
        print(result)
finally:
    connection.close()

# {'id':1, 'password': 'very-secret'}

 

3、connection对象

Representation of a socket with a mysql server.        与mysql建立socket

The proper way to get an instance of this class is to call connect().

Establish a connection to the MySQL database. Accepts several arguments:

参数:

class pymysql.connections.Connection(host=None, user=None, password='', database=None, port=0, unix_socket=None, charset='', sql_mode=None, read_default_file=None, conv=None, use_unicode=None, client_flag=0, cursorclass=<class 'pymysql.cursors.Cursor'>, init_command=None, connect_timeout=10, ssl=None, read_default_group=None, compress=None, named_pipe=None, no_delay=None, autocommit=False, db=None, passwd=None, local_infile=False, max_allowed_packet=16777216, defer_connect=False, auth_plugin_map={}, read_timeout=None, write_timeout=None, bind_address=None) 

host – Host where the database server is located
•user – Username to log in as
•password – Password to use.
•database – Database to use, None to not use a particular one.
•port – MySQL port to use, default is usually OK. (default: 3306)
•bind_address – When the client has multiple network interfaces, specify the interface from which to connect to the host. Argument can be a hostname or an IP address.
•unix_socket – Optionally, you can use a unix socket rather than TCP/IP.
•charset – Charset you want to use.
•sql_mode – Default SQL_MODE to use.
•read_default_file – Specifies my.cnf file to read these parameters from under the [client] section.
•conv – Conversion dictionary to use instead of the default one. This is used to provide custom marshalling and unmarshaling of types. See converters.
•use_unicode – Whether or not to default to unicode strings. This option defaults to true for Py3k.
•client_flag – Custom flags to send to MySQL. Find potential values in constants.CLIENT.
•cursorclass – Custom cursor class to use.
•init_command – Initial SQL statement to run when connection is established.
•connect_timeout – Timeout before throwing an exception when connecting. (default: 10, min: 1, max: 31536000)
•ssl – A dict of arguments similar to mysql_ssl_set()’s parameters. For now the capath and cipher arguments are not supported.
•read_default_group – Group to read from in the configuration file.
•compress – Not supported
•named_pipe – Not supported
•autocommit – Autocommit mode. None means use server default. (default: False)
•local_infile – Boolean to enable the use of LOAD DATA LOCAL command. (default: False)
•max_allowed_packet – Max size of packet sent to server in bytes. (default: 16MB) Only used to limit size of “LOAD LOCAL INFILE” data packet smaller than default (16KB).
•defer_connect – Don’t explicitly connect on contruction - wait for connect call. (default: False)
•auth_plugin_map – A dict of plugin names to a class that processes that plugin. The class will take the Connection object as the argument to the constructor. The class needs an authenticate method taking an authentication packet as an argument. For the dialog plugin, a prompt(echo, prompt) method can be used (if no authenticate method) for returning a string from the user. (experimental)
•db – Alias for database. (for compatibility to MySQLdb)
•passwd – Alias for password. (for compatibility to MySQLdb)
Parameters

相关文章:

  • 2022-12-23
猜你喜欢
  • 2021-10-03
相关资源
相似解决方案