java 如何将 Android Studio 与 SQL Server 数据库连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34938140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:34:00  来源:igfitidea点击:

How to connect Android Studio with SQL Server database

javaandroidsql-serverjdbc

提问by mtprogrammer

First, just tell me right off the bat if my attempts are futile by trying to connect Android Studio, a JVM-based IDE, with MS SQL Server. I do understand Oracle or MySQL would be better. However, I would like to try it.

首先,通过尝试将 Android Studio(一个基于 JVM 的 IDE)与 MS SQL Server 连接起来,如果我的尝试是徒劳的,请立即告诉我。我确实理解 Oracle 或 MySQL 会更好。但是,我想尝试一下。

I have successfully accessed a SQL Server database using Eclipse by adding an external dependency to the sqljdbc42.jar file and with some handy code provided by Microsoft (ignore the public static void main method...This was from Eclipse):

通过向 sqljdbc42.jar 文件添加外部依赖项并使用 Microsoft 提供的一些方便的代码(忽略 public static void main 方法...这是来自 Eclipse),我已经成功地使用 Eclipse 访问了 SQL Server 数据库:

//=====================================================================
//
//  File:    connectURL.java      
//  Summary: This Microsoft JDBC Driver for SQL Server sample application
//       demonstrates how to connect to a SQL Server database by using
//       a connection URL. It also demonstrates how to retrieve data 
//       from a SQL Server database by using an SQL statement.
//
//---------------------------------------------------------------------
//
//  This file is part of the Microsoft JDBC Driver for SQL Server Code Samples.
//  Copyright (C) Microsoft Corporation.  All rights reserved.
//
//  This source code is intended only as a supplement to Microsoft
//  Development Tools and/or on-line documentation.  See these other
//  materials for detailed information regarding Microsoft code samples.
//
//  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF 
//  ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO 
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//
//===================================================================== 

import java.sql.*;

public class connectURL {

public static void main(String[] args) {

    // Create a variable for the connection string.
    String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
        "databaseName=AdventureWorks2014;integratedSecurity=true;";

    // Declare the JDBC objects.
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;

        try {
            // Establish the connection.
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                con = DriverManager.getConnection(connectionUrl);

                // Create and execute an SQL statement that returns some data.
                String SQL = "SELECT TOP 10 * FROM Person.ContactType";
                stmt = con.createStatement();
                rs = stmt.executeQuery(SQL);

                // Iterate through the data in the result set and display it.
                while (rs.next()) {
                    System.out.println(rs.getString(1) + " " + rs.getString(2));
                }
        }

    // Handle any errors that may have occurred.
    catch (Exception e) {
        e.printStackTrace();
    }

    finally {
        if (rs != null) try { rs.close(); } catch(Exception e) {}
            if (stmt != null) try { stmt.close(); } catch(Exception e) {}
            if (con != null) try { con.close(); } catch(Exception e) {}
    }
}
}

Essentially, I took the same approach for Android Studio. I used the same JDBC 4.2 driver provided by Microsoft. In the build.gradle file I have tried adjusted the dependencies accordingly to accommodate for the new .jar file. Below is my build.gradle file:

本质上,我对 Android Studio 采取了相同的方法。我使用了 Microsoft 提供的相同 JDBC 4.2 驱动程序。在 build.gradle 文件中,我尝试相应地调整依赖项以适应新的 .jar 文件。下面是我的 build.gradle 文件:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '23.0.2'

    defaultConfig {
        applicationId "androidapp.dillon.betterhalf_v2"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"

        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    //compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.android.support:recyclerview-v7:23.1.1'
    compile files('libs/sqljdbc42.jar')
    }

You can see that I have commented out "compile fileTree(...)" This was by instruction from other posts I found. I also added the "multiDexEnabled true" line in my defaultConfig block per instruction.

你可以看到我已经注释掉了“compile fileTree(...)”这是我发现的其他帖子的说明。我还在每条指令的 defaultConfig 块中添加了“multiDexEnabled true”行。

The issue lies in the sqljdbc42.jar and adding it as a dependency. With it included, my project Builds, it Cleans, and it Rebuilds, but it does NOT Run or Debug. It generates an error(s) that I have found all over. Most posts on the error refer to the version of JDK I am using. I am using jdk1.8.0_71. I did try to target JDK 1.7. The error messages are as follows:

问题在于 sqljdbc42.jar 并将其添加为依赖项。包括它在内,我的项目构建、清理和重建,但它不运行或调试。它产生了一个我发现的错误。大多数关于错误的帖子都是指我正在使用的 JDK 版本。我正在使用 jdk1.8.0_71。我确实尝试以 JDK 1.7 为目标。错误信息如下:

Error 1:

错误 1:

Error:com.android.dx.cf.iface.ParseException: bad class file magic (cafebabe) or version (0034.0000)

Error 2:

错误 2:

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_71\bin\java.exe'' finished with non-zero exit value 1

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_71 \bin\java.exe'' 以非零退出值 1 结束

I apologize for the weird formatting. Thanks, for you help. Please comment if you need any more information.

我为奇怪的格式道歉。谢谢你的帮助。如果您需要更多信息,请发表评论。

回答by mtprogrammer

Found a workaround. Not much of an answer. Use a different JDBC driver provided by SourceForge instead of the one provided by Microsoft. Check it out here.

找到了解决方法。没有太多的答案。使用 SourceForge 提供的不同 JDBC 驱动程序,而不是 Microsoft 提供的驱动程序。检查它在这里

回答by Hendro Steven

Are you want to create an Android Apps that accessing SQL Server? If so, I'm afraid you can't. Android cannot access SQL Server directly, Android apps just a client app that need middle ware or services to access SQL Server. Your need to create the middle ware/services first with server side language ex. Java, PHP, .Net, Phyton, etc then your Android app call it with Http Connection

您想创建一个访问 SQL Server 的 Android 应用程序吗?如果是这样,恐怕你做不到。Android 不能直接访问 SQL Server,Android 应用程序只是需要中间件或服务来访问 SQL Server 的客户端应用程序。您需要首先使用服务器端语言创建中间件/服务。Java、PHP、.Net、Phyton 等,然后您的 Android 应用程序使用 Http Connection 调用它