简体   繁体   English

从Android应用程序访问SQL Server 2008中的数据

[英]Accessing data in SQL Server 2008 from an Android application

I'm new to Android development and have certain issue which is troubling me a lot, and worse is I haven't found the answer to it yet. 我是Android开发的新手,遇到了某些困扰我的问题,更糟糕的是我还没有找到答案。

Requirement: 需求:

1.) I'm developing Android app using eclipse as my base IDE. 1.)我正在使用eclipse作为基本IDE开发Android应用。 I have my data safely residing in SQLserver 2008. I don't want to use SQLite/MySql. 我的数据安全地驻留在SQLserver 2008中。我不想使用SQLite / MySql。

2.)Requirement here says, on a button click the application should talk to the SQLServer 2008 database, fetch data from it and list the data in the view. 2)这里的要求说,单击按钮,应用程序应该与SQLServer 2008数据库进行对话,从中获取数据并在视图中列出数据。

Is that possible?? 那可能吗?? If no then queries below this line are invalid. 如果否,则此行下方的查询无效。

Problem: 问题:

I tried to google it up providing queries like "Android and sqlserver connectivity", 我试图用Google搜索它,以提供“ Android和sqlserver连接”之类的查询,

"extracting data from sqlserver in Android" and ended up getting answers like below and I'm “从Android中的sqlserver提取数据”,最终得到如下所示的答案,我

losing track here. 在这里迷路。

1.) Some show it using a php scripting for My Sql but i'm using java and SQL Server 2008. I'm not getting the link here. 1.)有些人使用My Sql的php脚本显示它,但是我使用的是Java和SQL Server2008。我在这里没有链接。

2.) Some just say we have to use a Web Service to do it. 2)有些人只是说我们必须使用Web服务来完成它。 I tried understanding that but none of the examples showed implementing a web service and using it. 我试图理解,但是没有一个示例显示实现Web服务并使用它。 They just made a call to online available Web Service using KSoap to add 2 numbers. 他们刚刚使用KSoap拨打了在线可用Web服务的电话,以添加2个数字。

Query: 查询:

Is Web Service the only way in Android to communicate with a DB? Web服务是Android与数据库通信的唯一方法吗? If yes then how can i approach it. 如果是的话,我该如何处理。 Can anyone guide me as to 谁能指导我

1.) How to create a web service in Android application and call it from java code. 1.)如何在Android应用程序中创建Web服务并从Java代码调用它。

2.) How to talk to SQLServer 2008 DB from the webservice and fetch back the data. 2.)如何从Web服务与SQLServer 2008 DB进行对话并取回数据。

Any help is deeply appreciated, Thanks to all. 非常感谢任何帮助,谢谢大家。

This is a common topic on stackoverflow, you can find more information by searching. 这是关于stackoverflow的常见主题,您可以通过搜索找到更多信息。

The typical approach to your problem is to implement an Http API which will run on your server, perform database lookups, and respond to requests by clients, such as your Android application. 解决此问题的典型方法是实现一个Http API,该API将在您的服务器上运行,执行数据库查找并响应客户端(例如您的Android应用程序)的请求。 This way, you will not need to write any code to get your Android app to talk to your SQL server, but will instead be making standard Http requests, which is built-in on Android. 这样,您无需编写任何代码即可让您的Android应用程序与您的SQL Server通信,而将发出标准的Http请求,该请求是Android内置的。 On the other hand, you will need to write backend server code to handle these requests and respond with data from the database. 另一方面,您将需要编写后端服务器代码来处理这些请求并使用数据库中的数据进行响应。

So yes, you will probably need to implement a web server layer between the database and the Android client. 因此,是的,您可能需要在数据库和Android客户端之间实现Web服务器层。 It is possible to do it in Java or many other languages, you are not limited to Java just because your client is an Android app. 可以用Java或许多其他语言来实现,您不仅限于Java,因为您的客户端是Android应用程序。

Someone has already provided some information on just this topic here: 有人已经在这里提供了有关此主题的一些信息:
Connect to sql server from android 从Android连接到SQL Server
Connecting android with MS SQL SERVER 2008 将Android与MS SQL SERVER 2008连接

How to connect direct from Android to SQL Server. 如何直接从Android连接到SQL Server。

  1. You need the jtds-1.2.7.jar library. 您需要jtds-1.2.7.jar库。
  2. Set jtds-1.2.7.jar in libs file 在libs文件中设置jtds-1.2.7.jar

  3. Go to Dependencies and set 转到依赖项并设置

     compile files('libs/jtds-1.2.7.jar') 
  4. Create Connect_to_server.class 创建Connect_to_server.class

     import android.annotation.SuppressLint; import android.os.StrictMode; import android.util.Log; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class Connect_to_server { @SuppressLint("NewApi") public static Connection ConnectionHelper() { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() .permitAll().build(); StrictMode.setThreadPolicy(policy); Connection connection = null; String ConnectionURL = null; String user = ***LOGIN_HERE***; String password = ***PASSWORD_HERE***; String database = ***DATABASE_NAME_HERE***; String server= ***SERVER_NAME_HERE***; try { Class.forName("net.sourceforge.jtds.jdbc.Driver"); ConnectionURL = "jdbc:jtds:sqlserver://" + server + ";" + "databaseName=" + database + ";user=" + user + ";password=" + password + ";"; connection = DriverManager.getConnection(ConnectionURL); } catch (SQLException se) { Log.e("ERRO", se.getMessage()); } catch (ClassNotFoundException e) { Log.e("ERRO", e.getMessage()); } catch (Exception e) { Log.e("ERRO", e.getMessage()); } return connection; } } 
  5. In any other class or activity you need these three things 在任何其他课堂或活动中,您都需要这三件事

    • Connection 连接
    • Statement 声明
    • ResultSet 结果集
    1. Let's see how to use with this simple code 让我们看看如何使用这个简单的代码

       Connection connect; Statement st; Statement st1; ResultSet rs; btn_Register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { connect = Connect_to_server.ConnectionHelper(); st = connect.createStatement(); // TODO I will take ID_Admin from here rs = st.executeQuery(" SELECT * FROM [dbo].[AdminUsers] WHERE Email = N'"+ET_email.getText()+"' "); if (rs.next()){ Toast.makeText(getApplicationContext(),rs.getString("Email")+"this email in database",LENGTH_LONG).show(); Intent i = new Intent(RegisterActivity.this , LoginActivity.class); startActivity(i); finish(); }else{ reg(); } } catch (Exception e) { Log.e("ERRO", e.getMessage()); } } }); private void reg(){ try { connect = Connect_to_server.ConnectionHelper(); st1 = connect.createStatement(); st1.execute("INSERT INTO [dbo].[AdminUsers]" + " ([UserAdmin]" + " ,[PassAdmin]" + " ,[Address]" + " ,[Phone]" + " ,[Email])" + " VALUES" + " (N'"+ET_name.getText()+"'" + " ,N'"+ET_password.getText() +"'" + " ,N'"+ET_address.getText()+"'" + " ,N'"+ET_phone.getText()+"'" + " ,N'"+ET_email.getText()+"' )"); Toast.makeText(getApplicationContext(),ET_name.getText()+"welcome ",LENGTH_LONG).show(); Toast.makeText(getApplicationContext(),"u can login now",LENGTH_LONG).show(); Intent i = new Intent(RegisterActivity.this , LoginActivity.class); startActivity(i); finish(); } catch (Exception e) { Log.e("ERRO", e.getMessage()); Log.e("ERRO", e.getMessage()); } } 
    2. As we saw, we use st.executeQuery when we want to get data back and we set it in ResultSet, then fetch result set 如我们所见,当我们想取回数据时,我们使用st.executeQuery并将其设置在ResultSet中,然后获取结果集

      • while(rs.next()) when we have multiple records 当我们有多个记录时, while(rs.next())
      • if(rs.next()) when we are sure it's only one record if(rs.next())当我们确定它只是一个记录时
    3. st1.execute without return --- delete - insert - update st1.execute不返回---删除-插入-更新

    4. rs.getString("***Column_name_HERE***")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM