使用Chaquopy调用Python连接MS SQL Server时遇pyodbc模块缺失错误求解决
问题:Chaquopy集成Python连接MS SQL Server时出现ModuleNotFoundError: pyodbc
问题背景
近期尝试通过Chaquopy在Android的Java代码中调用Python脚本连接MS SQL Server,采用SQLAlchemy编写数据库连接代码,本地Shell运行正常,但集成到Android项目后应用崩溃。
Python数据库连接代码
from sqlalchemy import create_engine, text def test(): server = 'LAPTOP\SQLEXPRESS' database = 'test' driver = 'ODBC Driver 17 for SQL Server' dbconnection = f'mssql://@{server}/{database}?driver={driver}' engine = create_engine(dbconnection) connection = engine.connect() result = connection.execute(text("SELECT * FROM test_table")) test_result = "" for row in result: test_result += str(row) connection.close() return test_result test()
Java调用代码
package com.example.test3; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import com.chaquo.python.PyObject; import com.chaquo.python.Python; import com.chaquo.python.android.AndroidPlatform; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); TextView test = findViewById(R.id.test); test.setText(test()); } public String test(){ Python python = Python.getInstance(); PyObject pythonFile = python.getModule("test"); Log.v("TAG", "funkcja test dziala"); return pythonFile.callAttr("test").toString(); } public void init(){ if (! Python.isStarted()) { Python.start(new AndroidPlatform(this)); } } }
Logcat报错信息
FATAL EXCEPTION: main Process: com.example.test3, PID: 28531 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test3/com.example.test3.MainActivity}: com.chaquo.python.PyException: ModuleNotFoundError: No module named 'pyodbc'
模块级Gradle配置
plugins { id 'com.android.application' id 'com.chaquo.python' } android { namespace 'com.example.test3' compileSdk 33 defaultConfig { applicationId "com.example.test3" minSdk 24 targetSdk 33 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" ndk { abiFilters "armeabi-v7a", "arm64-v8a", "x86", "x86_64" } python { version "3.8" buildPython "C:\\Users\\48794\\AppData\\Local\\Programs\\Python\\Python38-32\\python.exe" } python { pip { install "SQLAlchemy" } } sourceSets { main { python.srcDir "src/main/python" } } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'com.google.android.material:material:1.5.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.4' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.5' androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' }
解决建议
1. 安装pyodbc依赖
报错直接提示缺少pyodbc模块,因为SQLAlchemy连接MS SQL Server依赖该库作为底层驱动。需要在Gradle的pip配置中添加安装:
修改Gradle中python的pip配置块:
python { pip { install "SQLAlchemy" install "pyodbc" } }
注意:pyodbc包含C扩展,Chaquopy需要编译它。确保buildPython版本与指定的Python版本一致,且本地安装了对应编译工具(如Windows下的Visual Studio Build Tools)。若编译失败,可尝试使用预编译wheel包,或参考Chaquopy文档确认支持的pyodbc版本。
2. 改用纯Python驱动(推荐)
Android环境默认没有ODBC驱动,即使安装pyodbc也无法直接使用系统级ODBC组件。更稳妥的方案是使用纯Python驱动,比如pymssql:
- 在Gradle中添加依赖:
python { pip { install "SQLAlchemy" install "pymssql" } }
- 修改Python代码的连接字符串:
dbconnection = f'mssql+pymssql://@{server}/{database}'
3. 网络与权限检查
确保AndroidManifest.xml中添加了网络权限:
<uses-permission android:name="android.permission.INTERNET"/>
同时验证设备能访问SQL Server实例,检查SQL Server是否允许远程连接、防火墙是否开放对应端口。
内容的提问来源于stack exchange,提问作者theprodigy133
相关产品推荐
相关产品推荐

