kms访问数据库的方式(该篇只是作为个人笔记,不具有任何公共参考意图)

项目类型:winform

语言:C#

服务程序:webservice(webservice我本人也不了解,在下一章中会总结一下对它的概念的简单理解)

情景描述:简单创建一个窗体,实现学生信息(姓名、性别)的新增和查询

一、保存按钮下的事件:

  private void btnSave_Click(object sender, EventArgs e)
{
try
{
List<SqlPara> list = new List<SqlPara>();
list.Add(new SqlPara("stuName",txtName.Text));
list.Add(new SqlPara("stuSex",txtSex.Text));
SqlParasEntity sps = new SqlParasEntity(OperType.Execute, "AddStudentInfo", list);
int result = SqlHelper.ExecuteNoQuery(sps);
if(result > )
{
MessageBox.Show("操作成功!");
return;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
return;
}
}

二、创建方法中使用到的类(使用一个类库统一管理这些类型)

 //参数对象
public class SqlPara
{
public string ParaName
{ get; set; }
public object ParaValue
{ get; set; }
public SqlPara(string n, object o)
{
this.ParaName = n;
this.ParaValue = o;
}
} //表示数据库操作类型
public enum OperType
{
Query = ,//查询 Execute = //执行
} //实例化对象(构造函数的重载,实现不同数据库操作的对象实例化)
public class SqlParasEntity
{
public OperType OperType
{ get; set; }
public string procedureName
{ get; set; }
public List<SqlPara> ParaList
{ get; set; }
public SqlParasEntity(OperType type, string proName, List<SqlPara> list)
{
OperType = type;
procedureName = proName;
ParaList = list;
}
public SqlParasEntity(OperType type,string proName)
{
OperType = type;
procedureName = proName;
}
}

三、第一大点中第九行的方法:int result = SqlHelper.ExecuteNoQuery(sps);

 namespace DAL
{
public class SqlHelper
{
private static int ver = ;
public static int ExecuteNoQuery(SqlParasEntity ent)
{
int flag = ExecuteNoQuery(ent, ver);
return flag;
}
private static int ExecuteNoQuery(SqlParasEntity ent, int ver)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable(ent.procedureName);
dt.Columns.Add("pname");
dt.Columns.Add("pvalue");
ds.Tables.Add(dt);
if (ent.ParaList == null)
{
List<SqlPara> list = new List<SqlPara>();
ent.ParaList = list;
}
foreach(var item in ent.ParaList)
{
if (item.ParaValue.GetType() == typeof(DataTable))
{
DataTable table = (item.ParaValue as DataTable).Copy();
table.TableName = item.ParaName;
ds.Tables.Add(table);
}
else
{
dt.Rows.Add(item.ParaName,item.ParaValue);
}
}
SqlResult result = new SqlResult();
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
SqlParasTable data = new SqlParasTable(ent.OperType,ds);
string json = JsonConvert.SerializeObject(data,settings);
result = HttpHelper.HttpPost(string.Format("ver={0}&json={1}",ver,json));
if (result.State == )
{
int count = ;
if (StringHelper.IsNumberId(result.Result))
{
count = Convert.ToInt32(result.Result);//这个为什么这样做
}
return count;
}
else
{
throw new Exception("返回信息:\r\n" + result.Result.Replace("数据库访问异常:","").Replace("错误信息","").Trim());
}
}
}
}

四、第三大点中41行代码方法:result = HttpHelper.HttpPost(string.Format("ver={0}&json={1}",ver,json));

1、先创建使用到的类型,三大点中36,39行

 public class SqlResult
{
/// <summary>
/// sql执行返回状态:1成功,2失败
/// </summary>
public int State
{ get; set; } /// <summary>
/// 如果state是1,则返回结果集(DataSet);State=0,返回错误信息
/// </summary>
public string Result
{ get; set; }
} /// <summary>
/// 数据库操作提交参数
/// </summary>
public class SqlParasTable
{
public OperType OperType
{ get; set; } /// <summary>
/// 参数集合,表类型
/// <para>第一个 table 是简单的数据类型,键值类型</para>
/// <para>第二 table 放表类型的参数(例如批量导入数据时)</para>
/// </summary>
public DataSet ParasDataSet
{ get; set; }
public SqlParasTable(OperType type,DataSet ds)
{
OperType = type;
ParasDataSet = ds;
}
}

2、三大点中41行方法:

 namespace DAL
{
class HttpHelper
{
public static string urlPage = "kms1.ashx";
// static string domain = "http://192.168.2.139:8090/";
static string domain = "http://localhost:28383/";
public static SqlResult HttpPost(string data)
{
string url = domain + urlPage;
SqlResult result = new SqlResult();
try
{
string json = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Proxy = null;
req.Method = "post";
req.ContentType = "application/x-www-form-urlencoded";
req.Timeout = ; byte[] btbody = Encoding.UTF8.GetBytes(data);
req.ContentLength = btbody.Length;
using (Stream st = req.GetRequestStream())
{
st.Write(btbody, , btbody.Length);
st.Close();
st.Dispose();
}
WebResponse wr = req.GetResponse();
using (StreamReader sr = new StreamReader(wr.GetResponseStream()))
{
json = sr.ReadToEnd();
sr.Close();
sr.Dispose();
}
wr.Close();
result = JsonConvert.DeserializeObject<SqlResult>(json);
}
catch (WebException ex)
{
result.State = ;
result.Result = "远程访问错误,\r\n" + ex.Message;
}
catch (Exception ex)
{
result.State = ;
result.Result = ex.Message;
}
return result;
}
}
}

章结尾:上面的数据库访问失败了。公司项目代码是这样的逻辑,但我没有使用过webservice服务,想自己搭建然后访问,但是没有成功。

上面的内容供自己参考一下数据传输的设计理念,后面要掌握一下webservice服务,实现数据访问

查询的操作方式和上面基本一致,将数据库放回结果转换为自己想要的数据类型即可(DataSet)

上一篇:jq ajax超时设置


下一篇:用php自带的filter函数验证、过滤数据 -转载