一、下载sql serever(真真难下)

建立数据库

二、创建WebService

VS2015中新建项目,进行连接调试

1. 服务资源管理文件->数据连接->新建连接

2. 继续->填写信息

3. 连接成功

4. 查看数据库属性并记录连接属性:

我的连接字符串为:Data Source=DESKTOP-AJOCHFK;Initial Catalog=myAndroid;Persist Security Info=True;User ID=sa;Password=***********

5. 新建WebService类,添加对数据库的各种操作

using System;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.IO; namespace WebApplication
{
public class DBOperation : IDisposable
{
public static SqlConnection sqlCon; //用于连接数据库 //将下面的引号之间的内容换成上面记录下的属性中的连接字符串Integrated Security=True
private String ConServerStr = @"Data Source=DESKTOP-AJOCHFK;Initial Catalog=myAndroid;Persist Security Info=True;User ID=sa;Password=123456"; //默认构造函数
public DBOperation()
{
if (sqlCon == null)
{
sqlCon = new SqlConnection();
sqlCon.ConnectionString = ConServerStr;
sqlCon.Open();
}
} //关闭/销毁函数,相当于Close()
public void Dispose()
{
if (sqlCon != null)
{
sqlCon.Close();
sqlCon = null;
}
} public List<string> selectAll()
{
List<string> list = new List<string>();
try
{
string sql = "select * from message";
SqlCommand cmd = new SqlCommand(sql, sqlCon);
SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read())
{
for (int i = ; i < ; i++)
{
list.Add(reader[i].ToString());
}
}
reader.Close();
cmd.Dispose();
}
catch(Exception)
{ }
return list;
} //longi——经度 lati——纬度
public bool message_add(string lati, string longi, string alti,string pm1d0s, string pm2d5s,
string pm10s, string pm1d0a, string pm2d5a, string pm10a,string pm0d3n,string pm0d5n,
string pm1d0n, string pm2d5n, string pm5n,string pm10n, string temp, string wet) //创建一条信息
{
bool result = false;
try
{
string sqls = "insert into message values('" + DateTime.Now.ToString() + "','" + lati + "','" + longi + "','"
+ alti + "','" + pm1d0s + "','" + pm2d5s + "','" + pm10s + "','" + pm1d0a + "','" + pm2d5a + "','" + pm10a + "','" +
pm0d3n + "','" + pm0d5n + "','" + pm1d0n + "','" + pm2d5n + "','" + pm5n + "','" + pm10n + "','" + temp + "','" + wet +"')";
SqlCommand cmd = new SqlCommand(sqls, sqlCon);
cmd.ExecuteNonQuery();
cmd.Dispose();
result = true;
}
catch (Exception e)
{
}
return result;
} public bool message_delete(string mNo)
{
bool result = false;
try
{
string sql = "delete from message where mNo=" + mNo;
SqlCommand cmd = new SqlCommand(sql, sqlCon);
cmd.ExecuteNonQuery();
cmd.Dispose();
result = true;
}
catch(Exception)
{ }
return result;
}
} }

6. 新建一个Web服务,如下

修改其代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services; namespace WebApplication
{
/// <summary>
/// WebService1 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
DBOperation DB = new DBOperation(); [WebMethod(Description ="获取所有的数据")]
public string[] selectallData()
{
return DB.selectAll().ToArray();
} [WebMethod(Description ="增加一条数据")]
public bool insertData(string lati, string longi, string alti, string pm1d0s,
string pm2d5s, string pm10s, string pm1d0a, string pm2d5a, string pm10a, string pm0d3n,
string pm0d5n, string pm1d0n, string pm2d5n,string pm5n, string pm10n, string temp , string wet)
{
return DB.message_add(lati, longi, alti, pm1d0s, pm2d5s, pm10s, pm1d0a, pm2d5a, pm10a, pm0d3n, pm0d5n, pm1d0n,
pm2d5n,pm5n, pm10n, temp, wet);
} [WebMethod(Description ="删除一条数据")]
public bool deleteData(string mNo)
{
return DB.message_delete(mNo);
}
}
}

7. 运行程序,打开google浏览器,页面如下

解决方法 :

尝试了 方法 http://jingyan.baidu.com/article/2d5afd69c5b7a585a2e28e8e.html ,没用

http://www.cnblogs.com/youring2/p/3545175.html, 没用

在 Web.config 中配置如下代码:

  <system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<!--重点是下面这句-->
<directoryBrowse enabled="true" />
<defaultDocument>
<files>
<add value="WebService1.asmx" />
</files>
</defaultDocument>
</system.webServer>

就出现了如下页面:

点开WebService1.asmx  就得到以下页面:

测试成功,返回值为xml

三、发布WebService

1. 右击项目,点击 ‘发布’

2. 然后 按照博客http://blog.csdn.net/bigpudding24/article/details/52291782 中的方法发布网站

出现以下问题:

解决方法:

打开  ‘启用或关闭windows功能’ ,在 ‘IIS’ 的 ‘万维网服务’ 中的 ‘应用程序开发功能’ 中 勾选如下选项,即可。

在浏览器中 输入 绑定的 IP 地址,即出现网站,发布成功。

四、Android客户端(从服务器获取数据,主要为Http类和AsyncTask类部分)

1. MainActivity.java

package org.example.myandroid;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast; import org.example.callback.RequestCallBack; import java.util.HashMap; public class MainActivity extends Activity{ private Button btn1;
private Button btn3;
private String requestUrl = "http://10.22.92.95/WebService1.asmx/deleteData"; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); btn1 = (Button) findViewById(R.id.btn_all);
btn3 = (Button) findViewById(R.id.btn_delete); btn1.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
setListView();
}
}); btn3.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
setDeleteDialog();
}
});
} /**
* 设置弹出删除对话框
*/
private void setDeleteDialog() { final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialog_delete);
dialog.setTitle("输入想要删除的数据的编号");
Window dialogWindow = dialog.getWindow();
WindowManager.LayoutParams lp = dialogWindow.getAttributes();
dialogWindow.setGravity(Gravity.CENTER);
dialogWindow.setAttributes(lp); final EditText cNoEditText = (EditText) dialog.findViewById(R.id.editText1);
Button btnConfirm = (Button) dialog.findViewById(R.id.button1);
Button btnCancel = (Button) dialog.findViewById(R.id.button2); btnConfirm.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
HashMap<String, String> callParams = new HashMap<String, String>();
callParams.put("mNo",cNoEditText.getText().toString());
MyAsyncTask restClient = new MyAsyncTask(new RequestCallBack() {
@Override
public void onSuccess(String response) {
//获取服务端返回的字符串
System.out.println("---------------------");
System.out.println(response);
}
@Override
public void onFailure() {
//获取失败
}
});
//第一个参数为选择POST或者GET
//第二个参数为请求的URL
//第三个参数为请求参数Map集合
Object[] params = { HttpTools.POST, requestUrl,
callParams };
restClient.execute(params); dialog.dismiss();
Toast.makeText(MainActivity.this, "成功删除数据", Toast.LENGTH_SHORT).show();
}
}); btnCancel.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
dialog.dismiss();
}
}); dialog.show();
} /**
* 设置listView
*/
private void setListView() { Intent intent = new Intent(MainActivity.this,ListAll.class);
startActivity(intent);
}
}

2. MyAsyncTask.java

package org.example.myandroid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry; public class HttpURLConnectionTools { /**
* @param strUrl
* @param params
* @return String
*/
public static String obtainGetUrlContext(String strUrl,
Map<String, String> params) {
String responseStr = "";
InputStream is = null;
HttpURLConnection conn = null;
BufferedReader bufferedReader = null;
try {
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(HttpTools.ReadOutTime /* milliseconds */);
conn.setConnectTimeout(HttpTools.ConnectOutTime /* milliseconds */);
conn.setRequestMethod(HttpTools.GET);
conn.setDoInput(true);
conn.connect();
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
bufferedReader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
responseStr += line;
}
}
} catch (Exception e) {
System.out.println("obtainGetUrlContext is err");
} finally {
if (is != null) {
try {
conn.disconnect();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return responseStr;
} /**
*
*
* @param strUrl
* @param params
* @return String
*/
public static String obtainPostUrlContext(String strUrl,
Map<String, String> params) {
String responseStr = "";
PrintWriter printWriter = null;
HttpURLConnection conn = null;
BufferedReader bufferedReader = null;
try {
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Length",
String.valueOf(PostRequestUrl(params).length()));
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(10000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
printWriter = new PrintWriter(conn.getOutputStream());
printWriter.write(PostRequestUrl(params).toString());
printWriter.flush();
int responseCode = conn.getResponseCode();
System.out.println(responseCode);
if (responseCode != 200) {
System.out.println("error");
} else {
bufferedReader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
responseStr += line;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
if (printWriter != null) {
printWriter.close();
}
}
return responseStr;
} /**
*
* @param params
* @return
* @throws UnsupportedEncodingException
*/
@SuppressWarnings("rawtypes")
private static StringBuffer PostRequestUrl(Map<String, String> params) {
StringBuffer buffers = new StringBuffer();
Iterator<Entry<String, String>> it = params.entrySet().iterator();
while (it.hasNext()) {
Map.Entry element = (Map.Entry) it.next();
buffers.append(element.getKey());
buffers.append("=");
buffers.append(element.getValue());
buffers.append("&");
System.out.println(buffers);
}
if (buffers.length() > 0) {
buffers.deleteCharAt(buffers.length() - 1);
}
return buffers;
}
}

3. HttpTools.java

package org.example.myandroid;

public class HttpTools {

    public static final String TAG = "HttpTools";
public static final String GET = "GET";
public static final String POST = "POST";
public static final int ReadOutTime = 100000;
public static final int ConnectOutTime = 100000;
public static final int ReadLength = 1024 * 500;
}

4. HttpURLConnectionTools.java

package org.example.myandroid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry; public class HttpURLConnectionTools { /**
* @param strUrl
* @param params
* @return String
*/
public static String obtainGetUrlContext(String strUrl,
Map<String, String> params) {
String responseStr = "";
InputStream is = null;
HttpURLConnection conn = null;
BufferedReader bufferedReader = null;
try {
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(HttpTools.ReadOutTime /* milliseconds */);
conn.setConnectTimeout(HttpTools.ConnectOutTime /* milliseconds */);
conn.setRequestMethod(HttpTools.GET);
conn.setDoInput(true);
conn.connect();
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
bufferedReader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
responseStr += line;
}
}
} catch (Exception e) {
System.out.println("obtainGetUrlContext is err");
} finally {
if (is != null) {
try {
conn.disconnect();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return responseStr;
} /**
*
*
* @param strUrl
* @param params
* @return String
*/
public static String obtainPostUrlContext(String strUrl,
Map<String, String> params) {
String responseStr = "";
PrintWriter printWriter = null;
HttpURLConnection conn = null;
BufferedReader bufferedReader = null;
try {
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Length",
String.valueOf(PostRequestUrl(params).length()));
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(10000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
printWriter = new PrintWriter(conn.getOutputStream());
printWriter.write(PostRequestUrl(params).toString());
printWriter.flush();
int responseCode = conn.getResponseCode();
System.out.println(responseCode);
if (responseCode != 200) {
System.out.println("error");
} else {
bufferedReader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
responseStr += line;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
if (printWriter != null) {
printWriter.close();
}
}
return responseStr;
} /**
*
* @param params
* @return
* @throws UnsupportedEncodingException
*/
@SuppressWarnings("rawtypes")
private static StringBuffer PostRequestUrl(Map<String, String> params) {
StringBuffer buffers = new StringBuffer();
Iterator<Entry<String, String>> it = params.entrySet().iterator();
while (it.hasNext()) {
Map.Entry element = (Map.Entry) it.next();
buffers.append(element.getKey());
buffers.append("=");
buffers.append(element.getValue());
buffers.append("&");
System.out.println(buffers);
}
if (buffers.length() > 0) {
buffers.deleteCharAt(buffers.length() - 1);
}
return buffers;
}
}

5. ListAll.java

package org.example.myandroid;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView; import org.example.callback.RequestCallBack; import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern; public class ListAll extends Activity{ private String requestUrl = "http://10.22.92.95/WebService1.asmx/selectallData";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_all);
MyAsyncTask restClient = new MyAsyncTask(new RequestCallBack() {
@Override
public void onSuccess(String response) {
//获取服务端返回的字符串
List list = getParameter(response,"string");
List<Message> messages= new ArrayList<Message>(); for(int i = 0;i < list.size(); i++)
{
list.set(i,removeAllSpace((String) list.get(i)));
} for(int i = 0; i < list.size();i+=18)
{
Message message = new Message(list.get(i).toString(),list.get(i+1).toString(),
list.get(i+2).toString(),list.get(i+3).toString(), list.get(i+4).toString(),
list.get(i+5).toString(),list.get(i+6).toString(),list.get(i+7).toString(),
list.get(i+11).toString(),list.get(i+12).toString(), list.get(i+13).toString(),
list.get(i+14).toString(),list.get(i+15).toString(),list.get(i+16).toString());
messages.add(message);
} final ListView listView = (ListView) findViewById(R.id.messages_list);
MessageAdapter adapter = new MessageAdapter(messages,ListAll.this);
listView.setAdapter(adapter);
}
@Override
public void onFailure() {
//获取失败
}
});
//第一个参数为选择POST或者GET
//第二个参数为请求的URL
//第三个参数为请求参数Map集合
Object[] params = { HttpTools.GET, requestUrl,
null };
restClient.execute(params); } public List<String> getParameter(String data,String para)
{
String result=""; String reg = "<string>" +"(.*?)"+"</string>"; Matcher matcher=Pattern.compile(reg).matcher(data); List<String> list = new ArrayList<String>();
while(matcher.find())
{
result=matcher.group(1);
list.add(result);
}
return list;
} public String removeAllSpace(String str)
{
String tmpstr=str.trim();
return tmpstr;
}
}

剩下的就是 很简单的数据类,和一些布局文件。

参考:http://blog.csdn.net/honyniu/article/details/38039343

WebService连接sql serever并使用Android端访问数据的更多相关文章

  1. 连接SQL SERVER 2008需要加端口号

    VC2010 ADO 连接SQL SERVER 2008,127.0.0.1,1433,要加上端口,否则连不上.注意:地址和端口之间使用逗号隔开. 连接SQL SERVER 2000可以不加端口号,使 ...

  2. windows 代理服务器的搭建,提供Android 端访问公网.

    这段时间遇到一个情况,移动的网络收费.但是可以访问学校内部的网络,比如说学校官网图书馆之类了.所以我这里便想到一个方法,用学校内部一个可以访问互联网的主机充当代理服务器(我这里使用自己的电脑,非服务器 ...

  3. Android -------- 网络访问数据

  4. 如何做好 Android 端音视频测试?

    在用户眼中,优秀的音视频产品应该具有清晰.低延时.流畅.秒开.抗丢包.高音效等特征.为了满足用户以上要求,网易云信的工程师通过自建源站,在SDK端为了适应网络优化进行QoS优化,对视频编码器进行优化, ...

  5. Android通过webservice连接SQLServer 详细教程(数据库+服务器+客户端)

    http://blog.csdn.net/zhyl8157121/article/details/8169172 目录(?)[-] 项目说明 开发环境的部署 数据库设计 服务器端程序设计Webserv ...

  6. Android 连接 SQL Server (jtds方式)——上

    本文将介绍开发Android程序,连接SQL Server,通过第三方包jtds的方式. 如果你有同样的需求,请跟着做一遍,博主将以最详细的方式,进行介绍. 首先说明,Java.Android连接SQ ...

  7. unity3d连接Sqlite并打包发布Android

    连接Sqlite首先要把dll程序集导入到unity3d工程里面.安装好的unity中可以找到

  8. [Android]Android端ORM框架——RapidORM(v2.1)

    以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/6020412.html [Android]Android端ORM ...

  9. [Android]Android端ORM框架——RapidORM(v2.0)

    以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/5626716.html [Android]Android端ORM ...

随机推荐

  1. Prolog学习:用八卦的精神走进Prolog

    最近枕头书是<七周七语言:理解多种编程范型>这本,前面两章分别看了Ruby和IO,都是命令式语言.虽然它们在语法上跟之前接触过的C,C#,Java这些C家族的语言差别很大,但是编程范型却是 ...

  2. WebService系列一:WebService简介

    原文链接:http://www.cnblogs.com/xdp-gacl/p/4259109.html 一.WebService是什么 WebService是一种跨编程语言和跨操作系统平台的远程调用技 ...

  3. 高校区LAN局域网校内网组建实践经验

    项目描述: ●校区计算机网络组建与管理和维护. 主要内容: 1.电脑故障诊断与排除与维护. 2.修复局域网内的故障电脑. 3.局域网架设虚拟系统. 4.局域网升级. 5.局域网基础架构. 6.电脑系统 ...

  4. #HTTP协议学习# (四)疑问篇

    1.为什么使用fiddler看不到旺旺客户端登录时发送的请求? 客户端是使用什么样的方式进行认证? 一般都是用HTTPS来加密Http request.  这样代理服务器就看不到里面的数据了.(why ...

  5. Linux Shell 基本语法

    一. Linux基本命令 1.1.  cp命令 该命令的功能是将给出的文件或目录拷贝到另一文件或目录中,功能十分强大. 语法: cp [选项] 源文件或目录 目标文件或目录 1.2. mv命令 用户可 ...

  6. Jenkins使用简易教程

    Jenkins是一款能提高效率的软件,它能帮你把软件开发过程形成工作流,典型的工作流包括以下几个步骤 开发 提交 编译 测试 发布 有了Jenkins的帮助,在这5步中,除了第1步,后续的4步都是自动 ...

  7. TensorFlow-Python:创建空列表list与append的用法

    1.空list的创建: l = list() 或者: l = [] 2.list中元素的创建和表达 fruits = ['apple', 'banana', 'pear', 'grapes', 'pi ...

  8. Linux学习笔记(二):实战-根据微服务端口号关闭进程

    前言 现在项目组基本都用Springboot,每个服务占用一个端口号,有时需要选择性的关闭,但在任务管理器上他们的名称都是java.exe,无法区分,这才学以致用. killPort.sh 作用:根据 ...

  9. 【Web API系列教程】3.3 — 实战:处理数据(建立数据库)

    前言 在本部分中,你将在EF上使用Code First Migration来用測试数据建立数据库. 在Tools文件夹下选择Library Package Manager,然后选择Package Ma ...

  10. keynote代码高亮【转】

    码农即使做ppt,也离不开代码,在keynote下,如果要粘贴代码,如何做到语法高亮呢? 补充1,该功能由pygments提供支持,所以支持的语言见:http://pygments.org/langu ...