WebService连接sql serever并使用Android端访问数据
一、下载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端访问数据的更多相关文章
- 连接SQL SERVER 2008需要加端口号
VC2010 ADO 连接SQL SERVER 2008,127.0.0.1,1433,要加上端口,否则连不上.注意:地址和端口之间使用逗号隔开. 连接SQL SERVER 2000可以不加端口号,使 ...
- windows 代理服务器的搭建,提供Android 端访问公网.
这段时间遇到一个情况,移动的网络收费.但是可以访问学校内部的网络,比如说学校官网图书馆之类了.所以我这里便想到一个方法,用学校内部一个可以访问互联网的主机充当代理服务器(我这里使用自己的电脑,非服务器 ...
- Android -------- 网络访问数据
- 如何做好 Android 端音视频测试?
在用户眼中,优秀的音视频产品应该具有清晰.低延时.流畅.秒开.抗丢包.高音效等特征.为了满足用户以上要求,网易云信的工程师通过自建源站,在SDK端为了适应网络优化进行QoS优化,对视频编码器进行优化, ...
- Android通过webservice连接SQLServer 详细教程(数据库+服务器+客户端)
http://blog.csdn.net/zhyl8157121/article/details/8169172 目录(?)[-] 项目说明 开发环境的部署 数据库设计 服务器端程序设计Webserv ...
- Android 连接 SQL Server (jtds方式)——上
本文将介绍开发Android程序,连接SQL Server,通过第三方包jtds的方式. 如果你有同样的需求,请跟着做一遍,博主将以最详细的方式,进行介绍. 首先说明,Java.Android连接SQ ...
- unity3d连接Sqlite并打包发布Android
连接Sqlite首先要把dll程序集导入到unity3d工程里面.安装好的unity中可以找到
- [Android]Android端ORM框架——RapidORM(v2.1)
以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/6020412.html [Android]Android端ORM ...
- [Android]Android端ORM框架——RapidORM(v2.0)
以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/5626716.html [Android]Android端ORM ...
随机推荐
- 模式识别之检索---Bag of visual word(词袋模型)
visual words 视觉单词 http://blog.csdn.net/v_july_v/article/details/8203674 http://blog.csdn.net/pi9nc/a ...
- (转)LCD:LCD常用接口原理篇
关键词:android LCD TFT TTL(RGB) LVDS EDP MIPI TTL-LVDS TTL-EDP平台信息:内核:linux2.6/linux3.0系统:android/a ...
- 导入Maven项目后,Eclipse提示“Missing artifact ”类的错误
导入Maven项目后,Eclipse提示“Missing artifact ”类的错误 标签: Maven Missing art 2016-08-15 16:05 679人阅读 评论(0) 收藏 举 ...
- Radix-64编码简介
本文介绍Radix-64编码,PGP和S/MIME均使用了Radix-64编码技术,rfc4880的Chap 6有关于Radix-64的详细描述. Radix-64编码基于Base64编码技术,由两部 ...
- WEB网页监控系统的设计框架思路具体解释
提示:也能够直接在LCD上显示摄像头数据.这个參考luvcview源代码.设计思路思将YUV或者MJPEG格式的数据转换成RGB格式的数据,然后实现图片的缩放,图像缩放算法:点击这里!,然后写到fra ...
- C# 获取文件大小
当然了都需要引入System.IO这个命名空间 第一个: public static long GetDirectoryLength(string dirPath){//判断给定的路径是否存在,如果不 ...
- [lua, mysql] 将多条记录数据组合成一条sql插入语句(for mysql)
-- 演示将多条记录数据组合成一条sql插入语句(for mysql) function getTpl0(tname) -- 获取表各个字段 local t = { tpl_pack = {" ...
- DShow + OpenGL播放视屏
#include <DShow.h> #pragma include_alias( "dxtrans.h", "qedit.h" ) #define ...
- Linq 查询某个字段为null的数据
如tb_flag 数据结构如下:flag int null 不能使用:flag==null 生成的SQL语句为 where flag=null 建议使用:可空类型 用Nullable<T&g ...
- daterangepicker日历插件使用参数注意问题
显示具体时间时分秒: timePicker设置为true,//有些资料写的pickerTime不太对 重点大坑:修改时间默认展示格式,把fomat写在locale中,网上很多资料说直接写在datera ...