Home » Python » Hướng dẫn cài đặt thư viện python mysqlclient Show
Hướng dẫn cài đặt thư viện python mysqlclient Cài đặt thư viện python mysqlclientTrên ubuntu ta cần phải cài sudo apt-get install libmysqlclient-dev pip install mysqlclient Trên Windows ta chỉ cần chạy lệnh: pip install mysqlclient Home » Python » Hướng dẫn cài đặt thư viện python mysqlclient Nội dung chính Hướng dẫn cài đặt thư viện python mysqlclient Cài đặt thư viện python mysqlclientTrên ubuntu ta cần phải cài sudo apt-get install libmysqlclient-dev pip install mysqlclient Trên Windows ta chỉ cần chạy lệnh: pip install mysqlclient This project is a fork of MySQLdb1. This project adds Python 3 support and fixed many bugs.
SupportDo Not use Github Issue Tracker to ask help. OSS Maintainer is not free tech support When your question looks relating to Python rather than MySQL:
Or when you have question about MySQL:
InstallWindowsBuilding mysqlclient on Windows is very hard. But there are some binary wheels you can install easily. If binary wheels do not exist for your version of Python, it may be possible to build from source, but if this does not work, do not come asking for support. To build from source, download the MariaDB C Connector and install it. It must be installed in the default location (usually "C:\Program
Files\MariaDB\MariaDB Connector C" or "C:\Program Files (x86)\MariaDB\MariaDB Connector C" for 32-bit). If you build the connector yourself or install it in a different location, set the environment variable
macOS (Homebrew)Install MySQL and mysqlclient:
If you don't want to install MySQL server, you can use mysql-client instead:
LinuxNote that this is a basic step. I can not support complete step for build for all environment. If you can see some error, you should fix it by yourself, or ask for support in some user forum. Don't file a issue on the issue tracker. You may need to install the Python 3 and MySQL development headers and libraries like so:
Then you can install mysqlclient via pip now:
Customize build (POSIX)mysqlclient uses You can use
DocumentationDocumentation is hosted on Read The Docs Home » Python » Hướng dẫn cài đặt thư viện python mysqlclient Nội dung chính
Hướng dẫn cài đặt thư viện python mysqlclient Cài đặt thư viện python mysqlclientTrên ubuntu ta cần phải cài sudo apt-get install libmysqlclient-dev pip install mysqlclient Trên Windows ta chỉ cần chạy lệnh: pip install mysqlclient MySQLdb User's GuideIntroductionMySQLdb is an interface to the popular MySQL database server that provides the Python database API. InstallationThe MySQLdb._mysqlIf you want to write applications which are portable across databases, use MySQLdb, and avoid using this module directly. MySQL C API translationThe MySQL C API has been wrapped in an object-oriented way. The only MySQL data structures which are implemented are the MySQL C API function mapping
Some _mysql examplesOkay, so you want to use The simplest possible database connection is: from MySQLdb import _mysql db=_mysql.connect() This creates a connection to the MySQL server running on the local machine using the standard UNIX socket (or named pipe on Windows), your login name (from the USER environment variable), no password, and does not db=_mysql.connect("localhost","joebob","moonpie","thangs") This creates a connection to the MySQL server running on the local machine via a UNIX socket (or named pipe), the user name "joebob", the password "moonpie", and selects the initial database "thangs". We haven't even begun to touch upon all the parameters db=_mysql.connect(host="localhost",user="joebob", password="moonpie",database="thangs") This does exactly what the last example did, but is arguably easier to read. But since the default host is "localhost", and if your login name really was "joebob", you could shorten it to this: db=_mysql.connect(password="moonpie",database="thangs") UNIX sockets and named pipes don't work over a network, so if you specify a host other than localhost, TCP will be used, and you can specify an odd port if you need to (the default port is 3306): db=_mysql.connect(host="outhouse",port=3307,password="moonpie",database="thangs") If you really had to, you could connect to the local host with TCP by specifying the full host name, or 127.0.0.1. Generally speaking, putting passwords in your code is not such a good idea: db=_mysql.connect(host="outhouse",database="thangs",read_default_file="~/.my.cnf") This does what the previous example does, but gets the username and password and other parameters from ~/.my.cnf (UNIX-like systems). Read about option files for more details. So now you have an open connection as db.query("""SELECT spam, eggs, sausage FROM breakfast WHERE price < 5""") There's no return value from this, but exceptions can be raised. The exceptions are defined in a separate module, At this point your query has been executed and you need to get the results. You have two options: r=db.store_result() # ...or... r=db.use_result() Both methods return a result object. What's the difference? Now, for actually getting real results: >>> r.fetch_row() (('3','2','0'),) This might look a
little odd. The first thing you should know is, The second parameter ( OK, so why did we get a 1-tuple with a tuple inside? Because we implicitly asked for one row, since we didn't specify The other oddity is: Assuming these are numeric columns, why
are they returned as strings? Because MySQL returns all data as strings and expects you to convert it yourself. This would be a real pain in the ass, but in fact, The keys of from MySQLdb.constants import FIELD_TYPE By default, any column type that can't be found in my_conv = { FIELD_TYPE.LONG: int } This means, if it's a Then if you use MySQLdbMySQLdb is a thin Python wrapper around The DB API specification PEP-249 should be your primary guide for using this module. Only deviations from the spec and other database-dependent things will be documented here. Functions and attributesOnly a few top-level functions and attributes are defined within MySQLdb. connect(parameters...)Constructor for creating a connection to the database. Returns a Connection Object. Parameters are the same as for the MySQL C API. In addition, there are a few additional keywords that correspond to
what you would pass MySQLdb.converters.conversions compressEnable protocol compression. Default: no compression.connect_timeoutAbort if connect is not completed within given number of seconds. Default: no timeout (?) named_pipeUse a named pipe (Windows). Default: don't.init_commandInitial command to
issue to server upon connection. Default: Nothing.read_default_fileMySQL configuration file to read; see the MySQL documentation for mysql_options() .read_default_groupDefault group to read; see the MySQL documentation for mysql_options() .cursorclasscursor class that cursor() uses, unless overridden. Default: MySQLdb.cursors.Cursor . This must be a keyword parameter.use_unicodeIf True, CHAR and VARCHAR and TEXT columns are returned as Unicode strings, using the configured character set. It is best to set the default encoding in the server configuration, or client configuration (read with read_default_file). If you change the character set after connecting (MySQL-4.1 and later), you'll need to put the correct character set name in connection.charset. If False, text-like columns are returned as normal strings, but you can always write Unicode strings. This must be a keyword parameter. charsetIf present, the connection character set will be changed to this character set, if they are not equal. Support for changing the character set requires MySQL-4.1 and later server; if the server is too old, UnsupportedError will be raised. This option implies use_unicode=True, but you can override this with use_unicode=False, though you probably shouldn't. If not present, the default character set is used. This must be a keyword parameter. sql_modeIf present, the session SQL mode will be set to the given string. For more information on sql_mode, see the MySQL documentation. Only available for 4.1 and newer servers. If not present, the session SQL mode will be unchanged. This must be a keyword parameter. ssl_modeIf present, specify the security settings for the connection to the server. For more information on ssl_mode, see the MySQL documentation. Only one of 'DISABLED', 'PREFERRED', 'REQUIRED', 'VERIFY_CA', 'VERIFY_IDENTITY' can be specified. If not present, the session ssl_mode will be unchanged, but in version 5.7 and later, the default is PREFERRED. This must be a keyword parameter. ssl This parameter takes a dictionary or mapping, where the keys are parameter names used by the mysql_ssl_set MySQL C API call. If this is set, it initiates an SSL connection to the server; if there is no SSL support in the client, an exception is raised. This must be a keyword parameter.apilevelString constant stating the supported DB API level. '2.0'threadsafetyInteger constant stating the level of thread safety the interface supports. This is set to 1, which means: Threads may share the module. The MySQL protocol can not handle multiple threads using the same connection at once. Some earlier versions of MySQLdb utilized locking to achieve a threadsafety of 2. While this is not terribly hard to accomplish using the standard Cursor class (which uses The general upshot of this is: Don't share connections between threads. It's really not worth your effort or mine, and in the end, will probably hurt performance, since the MySQL server runs a separate thread for each connection. You can certainly do things like cache connections in a pool, and give those connections to one thread at a time. If you let two threads use a connection simultaneously, the MySQL client library will probably upchuck and die. You have been warned. charsetThe character set used by the connection. In MySQL-4.1 and newer, it is possible (but not recommended) to change the connection's character set with an SQL statement. If you do this, you'll also need to change this attribute. Otherwise, you'll get encoding errors.paramstyleString constant stating the type of parameter marker formatting expected by the interface. Set to 'format' = ANSI C printf format codes, e.g. '...WHERE name=%s'. If a mapping object is used for conn.execute(), then the interface actually uses 'pyformat' = Python extended format codes, e.g. '...WHERE name=%(name)s'. However, the API does not presently allow the specification of more than one style in paramstyle. Note that any literal percent signs in the query string passed to execute() must be escaped, i.e. %%. Parameter placeholders can only be used to insert column values. They can not be used for other parts of SQL, such as table names, statements, etc. convA dictionary or mapping which controls how types are converted from MySQL to Python and vice versa. If the key is a MySQL type (from
If the key is a Python type or class, then the value is a callable Python object (usually a function) taking two arguments (value to convert, and the conversion dictionary) which converts values of this type to a SQL literal string value. This is initialized with reasonable defaults for most types. When creating a Connection object, you can pass your own type converter dictionary as a keyword parameter.
Otherwise, it uses a copy of Connection ObjectsConnection objects are returned by the NotSupportedError is raised.cursor([cursorclass])MySQL does not support cursors; however, cursors are easily emulated. You can supply an alternative cursor class as an optional parameter. If this is not present, it defaults to the value given when creating the connection object, or the standard Cursor class. Also see the additional supplied cursor classes in the usage section.There are many more methods defined on the
connection object which are MySQL-specific. For more information on them, consult the internal documentation using Cursor Objectscallproc(procname, args)Calls stored procedure procname with the sequence of arguments in args. Returns the original arguments. Stored procedure support only works with MySQL-5.0 and newer. Compatibility note: PEP-249 specifies that if there are OUT or INOUT parameters, the modified values are to be returned. This is not consistently possible with MySQL. Stored procedure arguments must be passed as server variables, and can only be returned with a SELECT statement. Since a stored procedure may return zero or more result sets, it is impossible for MySQLdb to determine if there are result sets to fetch before the modified parameters are accessible. The parameters are stored in the server as @_*procname*_*n*, where n is the position of the parameter. I.e., if you cursor.callproc('foo', (a, b, c)), the parameters will be accessible by a SELECT statement as @_foo_0, @_foo_1, and @_foo_2. Compatibility note: It appears that the mere act of executing the CALL statement produces an empty result set, which appears after any result sets which might be generated by the stored procedure. Thus, you will always need to use nextset() to advance result sets. close()Closes the cursor. Future operations raiseProgrammingError . If you are using server-side cursors, it is
very important to close the cursor when you are done with it and before creating a new one.info()Returns some information about the last query. Normally you don't need to check this. If there are any MySQL warnings, it will cause a Warning to be issued through the Python warning module. By default, Warning causes a message to appear on the console. However, it is possible to filter these out or cause Warning to be raised as exception. See the MySQL docs for mysql_info() , and the Python warning
module. (Non-standard)setinputsizes()Does nothing, successfully.setoutputsizes()Does nothing, successfully.nextset()Advances the cursor to the next result set, discarding the remaining rows in the current result set. If there are no additional result sets, it returns None; otherwise it returns a true value. Note that MySQL doesn't support multiple result sets until 4.1. Some examplesThe import MySQLdb db=MySQLdb.connect(password="moonpie",database="thangs") To perform a query, you first need a cursor, and then you can execute queries on it: c=db.cursor() max_price=5 c.execute("""SELECT spam, eggs, sausage FROM breakfast WHERE price < %s""", (max_price,)) In this example, Why the tuple? Because the DB API requires you to pass in any parameters as a sequence. Due to the design of the parser, (max_price) is interpreted as using algebraic grouping and simply as max_price and not a tuple. Adding a comma, i.e. (max_price,) forces it to make a tuple. And now, the results: >>> c.fetchone() (3L, 2L, 0L) Quite unlike the As mentioned earlier, while MySQL's INTEGER column translates perfectly into a Python integer, UNSIGNED INTEGER could overflow, so these values are converted to Python long integers instead. If you wanted more rows, you could use Note that in contrast to the above, The only other method you are very likely to use is when you have to do a multi-row insert: c.executemany( """INSERT INTO breakfast (name, spam, eggs, sausage, price) VALUES (%s, %s, %s, %s, %s)""", [ ("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ), ("Not So Much Spam Plate", 3, 2, 0, 3.95 ), ("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 ) ] ) Here we are inserting three rows of five values. Notice that there is a mix of types (strings, ints, floats) though we still only use Using and extendingIn general, it is probably wise to not directly interact with the DB API
except for small applications. Databases, even SQL databases, vary widely in capabilities and may have non-standard features. The DB API does a good job of providing a reasonably portable interface but some methods are non-portable. Specifically, the parameters accepted by If you believe your application may need to run on several different databases, the author recommends the following approach, based on personal experience: Write a simplified API for your application which implements the specific queries and operations your application needs to perform. Implement this API as a base class which should be have few database dependencies, and then derive a subclass from this which implements the necessary dependencies. In this way, porting your application to a new database should be a relatively simple matter of creating a new subclass, assuming the new database is reasonably standard. Because MySQLdb's Connection and Cursor objects are written in Python, you can easily derive your own subclasses. There are several Cursor classes in MySQLdb.cursors: BaseCursor The base class for Cursor objects. This does not raise Warnings.CursorStoreResultMixInCauses the Cursor to use themysql_store_result() function to get the query result. The entire result set is stored on the client side.CursorUseResultMixInCauses the cursor to use the mysql_use_result() function to get the query result. The result set is stored on the server side and is
transferred row by row using fetch operations.CursorTupleRowsMixInCauses the cursor to return rows as a tuple of the column values.CursorDictRowsMixInCauses the cursor to return rows as a dictionary, where the keys are column names and the values are column values. Note that if the column names are not unique, i.e., you are selecting from two tables that share column names, some of them will be rewritten as table.column . This can be avoided by using the SQL AS keyword. (This is yet-another
reason not to use * in SQL queries, particularly where JOIN is involved.)CursorThe default cursor class. This class is composed of CursorStoreResultMixIn , CursorTupleRowsMixIn , and BaseCursor , i.e. uses mysql_store_result() and returns rows as tuples.DictCursorLike Cursor except it returns rows as dictionaries.SSCursorA "server-side" cursor. Like Cursor but uses CursorUseResultMixIn . Use only if you are dealing with potentially large result sets.SSDictCursorLike SSCursor except it returns rows as dictionaries.
|