服务器端向mysql数据库写数据

using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.OleDb;
using System.Drawing;
using System.Data;
using MySQLDriverCS;
using System.Web.Script.Serialization; namespace GLSXJSON2.Controllers
{
public class AdviseInsertController : Controller
{ public string Index(string text) //这里的text是从service文件中获取的参数
{
MySQLConnection conn = null;
conn = new MySQLConnection(new MySQLConnectionString("localhost", "glsx", "root", "ecust2016", ).AsString);
conn.Open(); //这几句为建立一个MySQL的连接conn //sql语句写成string形式
string str0 = string.Format("select MAX(Id) from fag order by Id desc"); int id;
MySQLCommand cmd0 = new MySQLCommand(str0, conn); //建立MySQL执行命令cmd0 参数为str0和conn
if(cmd0.ExecuteScalar()!=null&&!Convert.IsDBNull(cmd0.ExecuteScalar())){//执行查询操作,ExecuteScalar()返回查询结果第一行
id=int.Parse(cmd0.ExecuteScalar().ToString())+; //这是不为空情况把id+1
}
else
id=; //若为空id置0 //sql语句写成string形式
string str = string.Format("insert into fag(Id,content) values({0},'{1}')", id, text); try
{
MySQLCommand cmd = new MySQLCommand(str, conn); //建立MySQL执行命令cmd 参数为str和conn
cmd.ExecuteNonQuery(); //返回执行的条数
return ""; //执行成功返回1
}
catch
{
return "-1"; //失败返回-1
} } }
}

服务器端从mysql数据库读数据

 using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.OleDb;
using System.Drawing;
using System.Data;
using MySQLDriverCS;
using System.Web.Script.Serialization; namespace GLSXJSON2.Controllers
{
public class OrderController : Controller
{ public JArray Index(string value,string id)
{
MySQLConnection conn = null;
conn = new MySQLConnection(new MySQLConnectionString("localhost", "glsx", "root", "ecust2016", ).AsString);
conn.Open();
//sql语句写成string形式
string str = string.Format("select placetime,price,cloth11,cloth12,cloth13,cloth14,cloth21,cloth22,cloth23 from `order` where status='{0}' and customer='{1}'", int.Parse(value),int.Parse(id)); //用conn连接数据库然后执行sql语句生成datatable
MySQLDataAdapter sda = new MySQLDataAdapter(str, conn);
DataTable dt = new DataTable();
sda.Fill(dt);//填充数据到dt //创建一个用以序列化的对象
JavaScriptSerializer jss = new JavaScriptSerializer();
//从datatable中逐列获取值到数组
System.Collections.ArrayList dic = new System.Collections.ArrayList();
foreach (DataRow dr in dt.Rows)
{
System.Collections.Generic.Dictionary<string, object> drow = new System.Collections.Generic.Dictionary<string, object>();
foreach (DataColumn dc in dt.Columns)
{
drow.Add(dc.ColumnName, dr[dc.ColumnName]);
}
dic.Add(drow);
}
conn.Close(); //将获取到的数列序列化以后转化为string然后再转化为JArray
return JArray.Parse(jss.Serialize(dic));
} }
}
05-26 05:57