這段代碼可以工作,但它只能插入一個json字符串到sql db。如果json字符串是多個,它將只插入一個json字符串,並且出現此錯誤插入多個json字符串時出錯
usp_insert_schedule指定的參數太多。
有人可以給我鏈接教程或指導我至少。
using Newtonsoft.Json;
//Object Root
public class jObt
{
public string empid { get; set; }
public string status { get; set; }
}
private void insrt_jString()
{
iScedule isc = new iScedule();
//sql stored proc
String Query = iSQL.STORED_PROCEDURE_SCH_ADD;
//sql class for insert
iEmp usr = new iEmp(Query);
string barc = txtBarCode.Text.Trim(' ');
string ddate = isc.get_date();
//http://get w/ barc & ddate as param
string input = isc.jValue(barc, ddate);
string input = @"{""empid"":""B14"",""status""}{""empid"":""B15"",""status"":""Morning""}";
var output = input.Split(new[] { '{', '}' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => "{" + x + "}")
.ToList();
foreach (var json in output)
{
jObt ob = JsonConvert.DeserializeObject<jObt>(json);
usr.Insert_Schedule(ob.empid, ob.status);
}
}
//Class for Insert_Schedule
public class iEmp: iCon
{
public string Query;
public string ComString { get; protected set; }
public iEmp(string ComS): base(ComS)
{
this.Query = ComS;
Comm.Parameters.Clear();
Comm.CommandType = CommandType.StoredProcedure;
Comm.CommandText = this.ComString;
Comm.Connection = Conn;
}
//SCHEDULE
public void Insert_Schedule(string empid, string status)
{
Comm.Parameters.AddWithValue("@empid", empid);
Comm.Parameters.AddWithValue("@status", status);
Comm.ExecuteNonQuery();
}
}
存儲過程根據您的循環低於
foreach (var json in output)
{
jObt ob = JsonConvert.DeserializeObject<jObt>(json);
usr.Insert_Schedule(ob.empid, ob.status);
}
你調用usr.Insert_Schedule
方法不止一次如果JSON包含多個對象
CREATE PROC [dbo].[usp_insert_schedule]
@empid [varchar](32),
@status [varchar](20)
AS
INSERT INTO Schedule(Ctrl_ID, Status)
VALUES (@empid, @status)
您可以編輯的問題,並添加'Insert_Schedule'方法和存儲過程的代碼下一組參數之前被清除的
Comm
參數? – ekad 2014-12-02 02:41:25它工作時,json字符串的值是一個但兩個或更多它不會:( – 2014-12-02 02:52:20
你爲什麼要解析(拆分等)的JSON字符串之前傳遞給'Newtonsoft.Json'?只是反序列化一個對象甚至是'動態'),並直接使用對象 – kaveman 2014-12-02 02:54:25