1.所需工具
1)VS2017 ;2)Postgis数据库
2.步骤
1)安装Npgsql类包
2)创建PgsqlHelper类(包括 增删改查操作的方法)
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using Npgsql;
namespace gis
{
public class PgsqlHelper
{
private static string connStr = @"PORT=5432;DATABASE=postgis;HOST=localhost;PASSWORD=postgres;USER ID=postgres";
#region 查询操作
public static DataTable ExecuteQuery(string sqrstr)
{
NpgsqlConnection sqlConn = new NpgsqlConnection(connStr);
DataTable ds = new DataTable();
try
{
using (NpgsqlDataAdapter sqldap = new NpgsqlDataAdapter(sqrstr, sqlConn))
{
sqldap.Fill(ds);
}
return ds;
}
catch (System.Exception ex)
{
// throw ex;
return ds;
}
}
#endregion
#region 增删改操作
public static int ExecuteNonQuery(string sqrstr, params NpgsqlParameter[] npgsqlParameters)
{
NpgsqlConnection sqlConn = new NpgsqlConnection(connStr);
try
{
sqlConn.Open();
using (NpgsqlCommand pgsqlCommand = new NpgsqlCommand(sqrstr, sqlConn))
{
foreach (NpgsqlParameter parm in npgsqlParameters)
pgsqlCommand.Parameters.Add(parm);
int r = pgsqlCommand.ExecuteNonQuery(); //执行查询并返回受影响的行数
sqlConn.Close();
return r; //r如果是>0操作成功!
}
}
catch (System.Exception ex)
{
return 0;
}
}
#endregion
}
}
3)编写一般处理程序页
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using Npgsql;
using Oracle.ManagedDataAccess.Client;
namespace gis
{
/// <summary>
/// Handler1 的摘要说明
/// </summary>
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
if (context.Request.HttpMethod.ToLower() == "post")
{
if (context.Request.QueryString["m"] == "Updatenosql")
{
//将字符串写入响应输出流(Updatenosql)
context.Response.Write(Updatenosql(context));
}
}
}
public string Updatenosql(HttpContext context)
{
string outdata = "";
string objectid = context.Request["objectid"];
string name = context.Request["name"];
string sql= "update hotel set name=:name where objectid=:objectid";
NpgsqlParameter[] parameters = {
new NpgsqlParameter(":objectid", int.Parse(objectid)),
new NpgsqlParameter(":name", name)
};
PgsqlHelper.ExecuteNonQuery(sql, parameters);
outdata = "更新成功";
return outdata;
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
4)前端js
$.ajax({
type: "post",
data: { objectid: 14, name:"龍港快捷宾馆-更新成功"},
url: "Handler1.ashx?m=Updatenosql",
dataType: "json",
success: function (data) {
console.log(data)
},
error: function (err) {
console.log(err.responseText)
}
});
3.结果