如何使用pip安装Python的MySQLdb模块?
答案 0 :(得分:479)
这很容易做到,但很难记住正确的拼写:
pip install mysqlclient
如果您需要1.2.x版本(仅限旧版Python),请使用pip install MySQL-python
注意:运行上述命令时可能必须使用某些依赖项。关于如何在各种平台上安装这些的一些提示:
sudo apt-get install python-pip python-dev libmysqlclient-dev
sudo dnf install python python-devel mysql-devel redhat-rpm-config gcc
brew install mysql-connector-c
如果失败,请尝试
brew install mysql
答案 1 :(得分:133)
从全新的Ubuntu 14.04.2系统开始,需要这两个命令:
apt-get install python-dev libmysqlclient-dev
pip install MySQL-python
只需执行" pip install"本身不起作用。
来自http://codeinthehole.com/writing/how-to-set-up-mysql-for-python-on-ubuntu/
答案 2 :(得分:21)
我在Windows上通过Pip安装64位版本的MySQLdb时出现问题(问题编译源)[32位版本安装好]。管理从http://www.lfd.uci.edu/~gohlke/pythonlibs/
提供的.whl文件安装已编译的MySQLdb然后可以通过pip将.whl文件安装为https://pip.pypa.io/en/latest/user_guide/#installing-from-wheels
中的文档例如,如果您保存在C:/
,则可以通过
pip install c:/MySQL_python-1.2.5-cp27-none-win_amd64.whl
跟进:如果你安装了64位版本的Python,那么你想从上面的链接安装64位AMD版本的MySQLdb [即即使你有英特尔处理器]。如果你试着安装32位版本,我认为你在下面的评论中得到了不支持的车轮错误。
答案 3 :(得分:16)
这对我有用:
pip install mysqlclient
这是针对python 3.x
答案 4 :(得分:11)
首先
pip install pymysql
然后将下面的代码放入__init__.py
(projectname/__init__.py
)
import pymysql
pymysql.install_as_MySQLdb()
我的环境是(python3.5,django1.10),这个解决方案对我有用!
希望这会有所帮助!!
答案 5 :(得分:6)
我尝试了所有选项,但无法让它在Redhat平台上运行。 我做了以下工作: -
yum install MySQL-python -y
安装软件包后,能够在解释器中按如下方式导入模块: -
>>> import MySQLdb
>>>
答案 6 :(得分:3)
如果您使用Raspberry Pi [Raspbian OS]
首先需要安装pip命令
apt-get install python-pip
所以只需安装Sequently
apt-get install python-dev libmysqlclient-dev
apt-get install python-pip
pip install MySQL-python
答案 7 :(得分:3)
您可以转到此website下载该软件包。
答案 8 :(得分:3)
转到pycharm然后转到默认设置 - > pip(双击) - pymsqldb ..-->安装 - 在这样的程序中安装使用后
package com.example.android.bluetoothlegatt;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
/**
* Service for managing connection and data communication with a GATT server hosted on a
* given Bluetooth LE device.
*/
public class BluetoothLeService extends Service {
private final static String TAG = BluetoothLeService.class.getSimpleName();
private BluetoothManager mBluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private String mBluetoothDeviceAddress;
private BluetoothGatt mBluetoothGatt;
private int mConnectionState = STATE_DISCONNECTED;
private static final int STATE_DISCONNECTED = 0;
private static final int STATE_CONNECTING = 1;
private static final int STATE_CONNECTED = 2;
public final static String ACTION_GATT_CONNECTED =
"com.example.bluetooth.le.ACTION_GATT_CONNECTED";
public final static String ACTION_GATT_DISCONNECTED =
"com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
public final static String ACTION_GATT_SERVICES_DISCOVERED =
"com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
public final static String ACTION_DATA_AVAILABLE =
"com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
public final static String EXTRA_DATA =
"com.example.bluetooth.le.EXTRA_DATA";
// Implements callback methods for GATT events that the app cares about. For example,
// connection change and services discovered.
private final BluetoothGattCallback mGattCallback;
{
mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
mConnectionState = STATE_CONNECTED;
broadcastUpdate(intentAction);
Log.i(TAG, "Connected to GATT server.");
// Attempts to discover services after successful connection.
Log.i(TAG, "Attempting to start service discovery:" +
mBluetoothGatt.discoverServices());
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
intentAction = ACTION_GATT_DISCONNECTED;
mConnectionState = STATE_DISCONNECTED;
Log.i(TAG, "Disconnected from GATT server.");
broadcastUpdate(intentAction);
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
setPuckCharacteristicNotification();
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.i(TAG, "onCharacteristicRead");
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
Log.i(TAG, "onCharacteristicChanged");
byte[] messageBytes = characteristic.getValue();
String messageString = null;
try {
messageString = new String(messageBytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Unable to convert message bytes to string");
}
Log.e(TAG, "Puck:" + messageString);
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
Log.i(TAG, "onCharacteristicWrite");
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
Log.i(TAG, "onDescriptorWrite");
BluetoothGattService service = gatt.getService(G.PUCK_SERVICE_UUID);
if (service != null) {
BluetoothGattCharacteristic characteristic =
service.getCharacteristic(G.PUCK_TX_UUID);
if (characteristic != null) {
Log.i(TAG, "Writing to characteristic " + characteristic.getUuid());
//String msg = "E.getTemperature()\n";
//byte[] data = msg.getBytes();
//characteristic.setValue(data);
if (gatt.writeCharacteristic(characteristic)) {
Log.i(TAG, "writeCharacteristic OK");
} else {
Log.i(TAG, "writeCharacteristic FAIL");
}
}
}
}
};
}
private void broadcastUpdate(final String action) {
final Intent intent = new Intent(action);
sendBroadcast(intent);
}
private void broadcastUpdate(final String action,
final BluetoothGattCharacteristic characteristic) {
final Intent intent = new Intent(action);
// This is special handling for the Heart Rate Measurement profile. Data parsing is
// carried out as per profile specifications:
// http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
if (G.PUCK_RX_UUID.equals(characteristic.getUuid())) {
int flag = characteristic.getProperties();
int format = -1;
/*if ((flag & 0x01) != 0) {
format = BluetoothGattCharacteristic.FORMAT_UINT16;
Log.i(TAG, "Heart rate format UINT16.");
} else {
format = BluetoothGattCharacteristic.FORMAT_UINT8;
Log.i(TAG, "Heart rate format UINT8.");
}*/
//final int heartRate = characteristic.getIntValue(format, 1);
//Log.i(TAG, String.format("Received heart rate: %d", heartRate));
//intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
} else {
// For all other profiles, writes the data formatted in HEX.
final byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
final StringBuilder stringBuilder = new StringBuilder(data.length);
for (byte byteChar : data)
stringBuilder.append(String.format("%02X ", byteChar));
intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
}
}
sendBroadcast(intent);
}
public class LocalBinder extends Binder {
BluetoothLeService getService() {
return BluetoothLeService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
// After using a given device, you should make sure that BluetoothGatt.close() is called
// such that resources are cleaned up properly. In this particular example, close() is
// invoked when the UI is disconnected from the Service.
close();
return super.onUnbind(intent);
}
private final IBinder mBinder = new LocalBinder();
/**
* Initializes a reference to the local Bluetooth adapter.
*
* @return Return true if the initialization is successful.
*/
public boolean initialize() {
// For API level 18 and above, get a reference to BluetoothAdapter through
// BluetoothManager.
if (mBluetoothManager == null) {
mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
if (mBluetoothManager == null) {
Log.e(TAG, "Unable to initialize BluetoothManager.");
return false;
}
}
mBluetoothAdapter = mBluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
return false;
}
return true;
}
/**
* Connects to the GATT server hosted on the Bluetooth LE device.
*
* @param address The device address of the destination device.
* @return Return true if the connection is initiated successfully. The connection result
* is reported asynchronously through the
* {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public boolean connect(final String address) {
if (mBluetoothAdapter == null || address == null) {
Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
return false;
}
// Previously connected device. Try to reconnect.
if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
&& mBluetoothGatt != null) {
Log.i(TAG, "Trying to use an existing mBluetoothGatt for connection.");
if (mBluetoothGatt.connect()) {
mConnectionState = STATE_CONNECTING;
return true;
} else {
return false;
}
}
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
Log.w(TAG, "Device not found. Unable to connect.");
return false;
}
// We want to directly connect to the device, so we are setting the autoConnect
// parameter to false.
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
Log.i(TAG, "Trying to create a new connection.");
mBluetoothDeviceAddress = address;
mConnectionState = STATE_CONNECTING;
return true;
}
/**
* Disconnects an existing connection or cancel a pending connection. The disconnection result
* is reported asynchronously through the
* {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public void disconnect() {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.disconnect();
}
/**
* After using a given BLE device, the app must call this method to ensure resources are
* released properly.
*/
public void close() {
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}
/**
* Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
* asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
* callback.
*
* @param characteristic The characteristic to read from.
*/
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.readCharacteristic(characteristic);
}
/**
* Enables notification on a given characteristic.
**/
public void setPuckCharacteristicNotification() {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
//Start getting data
BluetoothGattService gattService = mBluetoothGatt.getService(G.PUCK_SERVICE_UUID);
if (gattService != null) {
BluetoothGattCharacteristic gattCharacteristic = gattService.getCharacteristic(G.PUCK_RX_UUID);
if (gattCharacteristic != null) {
Log.i(TAG, "Setting Characteristic " + gattCharacteristic.getUuid());
mBluetoothGatt.setCharacteristicNotification(gattCharacteristic, true);
BluetoothGattDescriptor clientDescriptor = gattCharacteristic.getDescriptor(G.CLIENT_CHARACTERISTIC_CONFIG);
clientDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(clientDescriptor);
}
}
}
/**
* Retrieves a list of supported GATT services on the connected device. This should be
* invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.
*
* @return A {@code List} of supported services.
*/
public List<BluetoothGattService> getSupportedGattServices() {
if (mBluetoothGatt == null) return null;
return mBluetoothGatt.getServices();
}
public int getElement(byte[] arrayOfBytes, int index) {
return arrayOfBytes[index];
}
}
答案 9 :(得分:2)
这里给出的许多答案都相当令人困惑,因此我将尝试简单地说明一下。它帮助我安装了此
pip install pymysql
,然后在python文件中使用以下命令
import pymysql as MySQLdb
这样,您可以毫无问题地使用MySQLdb。
答案 10 :(得分:2)
如果无法安装 mysqlclient ,也可以安装 pymysql :
pip install pymysql
这与 MySqldb 相同。之后,使用pymysql代替MySQLdb
答案 11 :(得分:2)
我也有同样的问题。如果你在Windows上,请执行以下步骤。 去: 我的电脑 2.系统属性 3.Advance系统设置 4.在“高级”选项卡下,单击“环境变量”按钮 5.然后在系统变量下,您必须添加/更改以下变量:PYTHONPATH和Path。这是我的变量看起来像的粘贴: python路径:
C:\Python27;C:\Python27\Lib\site-packages;C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\Python27\Scripts
路径:
C:\Program Files\MySQL\MySQL Utilities 1.3.5\;C:\Python27;C:\Python27\Lib\site-packages;C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\Python27\Scripts
请参阅此 link 以供参考
答案 12 :(得分:1)
pip install mysql-connector-python
如文档中所述:
https://dev.mysql.com/doc/connector-python/en/connector-python-installation-binary.html
答案 13 :(得分:1)
上面的答案很好,但是当我们使用pip在 Windows
中安装MySQL-python时可能会出现一些问题例如,它需要一些与 Visual Stdio 相关联的文件。一个解决方案是安装VS2008或2010 ......显然,它的成本太高。
另一种方法是@ bob90937的答案。我在这里做点什么补充。
使用http://www.lfd.uci.edu/~gohlke/pythonlibs,您可以下载许多科学开源扩展包的Windows二进制文件,用于Python编程语言的官方CPython发行版。
回到主题,我们可以选择 MySQL-python(py2)或 Mysqlclient(py3)并使用 pip install 进行安装。它给了我们极大的便利!
答案 14 :(得分:1)
在RHEL 7上:
<div class="imagefloatright">
<p>Step 1</p>
<img src="http://via.placeholder.com/80x80"/>
</div>
<div class="imagefloatright">
<p>Step 2</p>
<img src="http://via.placeholder.com/80x80"/>
</div>
sudo yum install yum-utils mariadb-devel python-pip python-devel gcc
答案 15 :(得分:0)
如果pip3不起作用,您可以尝试:
"sonata-bundle/admin-bundle": "*",
答案 16 :(得分:0)
对于Python3,我需要这样做:
python3 -m pip install MySQL
答案 17 :(得分:0)
如果您的系统上安装了Windows,则在cmd上键入以下命令:
pip install mysql-connector
如果上述命令不起作用,请尝试使用:
pip install mysql-connector-python
现在,如果以上命令无法完成工作,请尝试使用:
pip install mysql-connector-python-rf
就是这样,您现在就可以走了。
答案 18 :(得分:0)
我的环境是:
pip安装mysqlclient-1.3.13-cp37-cp37m-win_amd64.whl
为我工作。
import MySQLdb, sys
# --------------------------------------------------
# Connect to MySQL
# --------------------------------------------------
try:
db = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="database", charset='cp1251')
except MySQLdb.Error as e:
print ("Error %d: %s" % (e.args[0], e.args[1]))
sys.exit()
# Creating cursor
cursor = db.cursor()
答案 19 :(得分:0)
实际上,按照@Nick T的回答对我不起作用,我尝试apt-get install python-mysqldb
对我有用
root@2fb0da64a933:/home/test_scrapy# apt-get install python-mysqldb
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
libmariadbclient18 mysql-common
Suggested packages:
default-mysql-server | virtual-mysql-server python-egenix-mxdatetime python-mysqldb-dbg
The following NEW packages will be installed:
libmariadbclient18 mysql-common python-mysqldb
0 upgraded, 3 newly installed, 0 to remove and 29 not upgraded.
Need to get 843 kB of archives.
After this operation, 4611 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://deb.debian.org/debian stretch/main amd64 mysql-common all 5.8+1.0.2 [5608 B]
Get:2 http://deb.debian.org/debian stretch/main amd64 libmariadbclient18 amd64 10.1.38-0+deb9u1 [785 kB]
Get:3 http://deb.debian.org/debian stretch/main amd64 python-mysqldb amd64 1.3.7-1.1 [52.1 kB]
Fetched 843 kB in 23s (35.8 kB/s)
debconf: delaying package configuration, since apt-utils is not installed
Selecting previously unselected package mysql-common.
(Reading database ... 13223 files and directories currently installed.)
Preparing to unpack .../mysql-common_5.8+1.0.2_all.deb ...
Unpacking mysql-common (5.8+1.0.2) ...
Selecting previously unselected package libmariadbclient18:amd64.
Preparing to unpack .../libmariadbclient18_10.1.38-0+deb9u1_amd64.deb ...
Unpacking libmariadbclient18:amd64 (10.1.38-0+deb9u1) ...
Selecting previously unselected package python-mysqldb.
Preparing to unpack .../python-mysqldb_1.3.7-1.1_amd64.deb ...
Unpacking python-mysqldb (1.3.7-1.1) ...
Setting up mysql-common (5.8+1.0.2) ...
update-alternatives: using /etc/mysql/my.cnf.fallback to provide /etc/mysql/my.cnf (my.cnf) in auto mode
Setting up libmariadbclient18:amd64 (10.1.38-0+deb9u1) ...
Processing triggers for libc-bin (2.24-11+deb9u3) ...
Setting up python-mysqldb (1.3.7-1.1) ...
root@2fb0da64a933:/home/test_scrapy# python
Python 2.7.13 (default, Nov 24 2017, 17:33:09)
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
>>>