我正在尝试将数组呼叫经销商传递给webservices以插入到MSSQL 2012表中。
<script>
var dealers = new Array();
dealers.push(new Array("123", "870503-23-5370", "021"));
dealers.push(new Array("456", "830503-23-5371", "031"));
dealers.push(new Array("789", "870103-11-5372", "041"));
dealers.push(new Array("654", "870501-23-5373", "051"));
dealers.push(new Array("321", "880503-12-5374", "061"));
dealers.push(new Array("987", "870803-23-5375", "071"));
dealers.push(new Array("109", "870508-06-5376", "081"));
dealers.push(new Array("174", "810503-03-5377", "091"));
dealers.push(new Array("509", "870103-01-5378", "101"));
dealers.push(new Array("687", "870501-12-5379", "131"));
$(document).ready( function() {
$('#btnSubmit').click(function() {
$.ajax({
type: "post",
url: "Service1.asmx/DailyCheckDealer",
data: JSON.stringify({ records: dealers }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onSuccess,
failure: onError
});
});
})
function onSuccess(response) {
alert(response.d);
}
function onError() {
alert("fail");
}
</script>
我还是ASP.NET VB的新手。有人可以帮我提供示例代码,如何处理数组并插入数据库。
Public Class Service1
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function DailyCheckDealer() As String
"How process the array and inserted into database"
End Function
End Class
更新:
如果我的网络服务改变如下:
<WebMethod()> _
Public Function DailyCheckDealer(records As String()()) As String
Dim mylist As List(Of String()) = records.ToList()
Dim datarow As String = ""
Dim result As String = "Done"
For i As Integer = 0 To mylist.Count - 1
Dim m As String() = mylist(i)
For j As Integer = 0 To m.Length - 1
datarow += m(j) + " "
Dim objDealer As New Dealer
Dim myConnString = System.Configuration.ConfigurationManager.AppSettings("MY_CONNECTION")
Dim myConnection = New SqlConnection(myConnString)
Dim myCommand = New SqlCommand()
myCommand.CommandType = CommandType.StoredProcedure
myCommand.Connection = myConnection
myCommand.CommandText = "DailyCheckDealer"
myCommand.Parameters.Add("@DataRow", SqlDbType.VarChar, 22).Value = datarow
myConnection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()
Next
Next
Return result
End Function
据说它应该在数据库中插入10条记录,但是对于我的结果,它只插入第一条记录。
更新
抱歉,我的结果错误信息。整个记录被插入数据库而不是10条记录。
答案 0 :(得分:0)
您将需要下面的2个db对象。第一个是用户定义的表类型,第二个是json解析存储过程:
CREATE TYPE [dbo].[typHierarchy] AS TABLE(
[element_id] [int] IDENTITY(1,1) NOT NULL,
[sequenceNo] [int] NULL,
[parent_ID] [int] NULL,
[Object_ID] [int] NULL,
[NAME] [nvarchar](2000) NULL,
[StringValue] [nvarchar](max) NOT NULL,
[ValueType] [varchar](10) NOT NULL,
PRIMARY KEY CLUSTERED
(
[element_id] ASC
)WITH (IGNORE_DUP_KEY = OFF)
)
/*
taken from https://www.simple-talk.com/sql/t-sql-programming/consuming-json-strings-in-sql-server/
*/
CREATE PROC dbo.spParseJSON
@strJSON NVARCHAR(MAX)--, @strColumnList VARCHAR(2000)
AS
--SET @strJSON = REPLACE(@strJSON,'\','')
DECLARE @objJSONTable typHierarchy
DECLARE @FirstObject INT, --the index of the first open bracket found in the JSON string
@OpenDelimiter INT,--the index of the next open bracket found in the JSON string
@NextOpenDelimiter INT,--the index of subsequent open bracket found in the JSON string
@NextCloseDelimiter INT,--the index of subsequent close bracket found in the JSON string
@Type NVARCHAR(10),--whether it denotes an object or an array
@NextCloseDelimiterChar CHAR(1),--either a '}' or a ']'
@Contents NVARCHAR(MAX), --the unparsed contents of the bracketed expression
@Start INT, --index of the start of the token that you are parsing
@end INT,--index of the end of the token that you are parsing
@param INT,--the parameter at the end of the next Object/Array token
@EndOfName INT,--the index of the start of the parameter at end of Object/Array token
@token NVARCHAR(200),--either a string or object
@value NVARCHAR(MAX), -- the value as a string
@SequenceNo int, -- the sequence number within a list
@name NVARCHAR(200), --the name as a string
@parent_ID INT,--the next parent ID to allocate
@lenJSON INT,--the current length of the JSON String
@characters NCHAR(36),--used to convert hex to decimal
@result BIGINT,--the value of the hex symbol being parsed
@index SMALLINT,--used for parsing the hex value
@Escape INT --the index of the next escape character
DECLARE @Strings TABLE /* in this temporary table we keep all strings, even the names of the elements, since they are 'escaped' in a different way, and may contain, unescaped, brackets denoting objects or lists. These are replaced in the JSON string by tokens representing the string */
(String_ID INT IDENTITY(1, 1),
StringValue NVARCHAR(MAX))
SELECT--initialise the characters to convert hex to ascii
@characters='0123456789abcdefghijklmnopqrstuvwxyz',
@SequenceNo=0, --set the sequence no. to something sensible.
/* firstly we process all strings. This is done because [{} and ] aren't escaped in strings, which complicates an iterative parse. */
@parent_ID=0;
WHILE 1=1 --forever until there is nothing more to do
BEGIN
SELECT @start=PATINDEX('%[^a-zA-Z]["]%', @strJSON collate SQL_Latin1_General_CP850_Bin);--next delimited string
IF @start=0 BREAK --no more so drop through the WHILE loop
IF SUBSTRING(@strJSON, @start+1, 1)='"'
BEGIN --Delimited Name
SET @start=@Start+1;
SET @end=PATINDEX('%[^\]["]%', RIGHT(@strJSON, LEN(@strJSON+'|')-@start) collate SQL_Latin1_General_CP850_Bin);
END
IF @end=0 --no end delimiter to last string
BREAK --no more
SELECT @token=SUBSTRING(@strJSON, @start+1, @end-1)
--now put in the escaped control characters
SELECT @token=REPLACE(@token, FROMString, TOString)
FROM
(SELECT '\"' AS FromString, '"' AS ToString
UNION ALL SELECT '\\', '\'
UNION ALL SELECT '\/', '/'
UNION ALL SELECT '\b', CHAR(08)
UNION ALL SELECT '\f', CHAR(12)
UNION ALL SELECT '\n', CHAR(10)
UNION ALL SELECT '\r', CHAR(13)
UNION ALL SELECT '\t', CHAR(09)) substitutions
SELECT @result=0, @escape=1
--Begin to take out any hex escape codes
WHILE @escape>0
BEGIN
SELECT @index=0,
--find the next hex escape sequence
@escape=PATINDEX('%\x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%', @token collate SQL_Latin1_General_CP850_Bin)
IF @escape>0 --IF there is one
BEGIN
WHILE @index<4 --there are always four digits to a \x sequence
BEGIN
SELECT --determine its value
@result=@result+POWER(16, @index)
*(CHARINDEX(SUBSTRING(@token, @escape+2+3-@index, 1),
@characters)-1), @index=@index+1 ;
END
-- and replace the hex sequence by its unicode value
SELECT @token=STUFF(@token, @escape, 6, NCHAR(@result))
END
END
--now store the string away
INSERT INTO @Strings (StringValue) SELECT @token
-- and replace the string with a token
SELECT @strJSON=STUFF(@strJSON, @start, @end+1,
'@string'+CONVERT(NVARCHAR(5), @@identity))
END
-- all strings are now removed. Now we find the first leaf.
WHILE 1=1 --forever until there is nothing more to do
BEGIN
SELECT @parent_ID=@parent_ID+1
--find the first object or list by looking for the open bracket
SELECT @FirstObject=PATINDEX('%[{[[]%', @strJSON collate SQL_Latin1_General_CP850_Bin)--object or array
IF @FirstObject = 0 BREAK
IF (SUBSTRING(@strJSON, @FirstObject, 1)='{')
SELECT @NextCloseDelimiterChar='}', @type='object'
ELSE
SELECT @NextCloseDelimiterChar=']', @type='array'
SELECT @OpenDelimiter=@firstObject
WHILE 1=1 --find the innermost object or list...
BEGIN
SELECT @lenJSON=LEN(@strJSON+'|')-1
--find the matching close-delimiter proceeding after the open-delimiter
SELECT @NextCloseDelimiter=CHARINDEX(@NextCloseDelimiterChar, @strJSON,
@OpenDelimiter+1)
--is there an intervening open-delimiter of either type
SELECT @NextOpenDelimiter=PATINDEX('%[{[[]%',
RIGHT(@strJSON, @lenJSON-@OpenDelimiter)collate SQL_Latin1_General_CP850_Bin)--object
IF @NextOpenDelimiter=0 BREAK
SELECT @NextOpenDelimiter=@NextOpenDelimiter+@OpenDelimiter
IF @NextCloseDelimiter<@NextOpenDelimiter BREAK
IF SUBSTRING(@strJSON, @NextOpenDelimiter, 1)='{'
SELECT @NextCloseDelimiterChar='}', @type='object'
ELSE
SELECT @NextCloseDelimiterChar=']', @type='array'
SELECT @OpenDelimiter=@NextOpenDelimiter
END
---and parse out the list or name/value pairs
SELECT @contents=SUBSTRING(@strJSON, @OpenDelimiter+1,
@NextCloseDelimiter-@OpenDelimiter-1)
SELECT @strJSON=STUFF(@strJSON, @OpenDelimiter,
@NextCloseDelimiter-@OpenDelimiter+1,
'@'+@type+CONVERT(NVARCHAR(5), @parent_ID))
WHILE (PATINDEX('%[A-Za-z0-9@+.e]%', @contents collate SQL_Latin1_General_CP850_Bin))<>0
BEGIN
IF @Type='Object' --it will be a 0-n list containing a string followed by a string, number,boolean, or null
BEGIN
SELECT @SequenceNo=0,@end=CHARINDEX(':', ' '+@contents)--IF there is anything, it will be a string-based name.
SELECT @start=PATINDEX('%[^A-Za-z@][@]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)--AAAAAAAA
SELECT @token=SUBSTRING(' '+@contents, @start+1, @End-@Start-1),
@endofname=PATINDEX('%[0-9]%', @token collate SQL_Latin1_General_CP850_Bin),
@param=RIGHT(@token, LEN(@token)-@endofname+1)
SELECT @token=LEFT(@token, @endofname-1),
@Contents=RIGHT(' '+@contents, LEN(' '+@contents+'|')-@end-1)
SELECT @name=stringvalue FROM @strings WHERE string_id=@param --fetch the name
END
ELSE
SELECT @Name=null,@SequenceNo=@SequenceNo+1
SELECT @end=CHARINDEX(',', @contents)-- a string-token, object-token, list-token, number,boolean, or null
--for debugging|start
--SELECT [@startxxx] = @start
--for debugging|end
IF @end=0
SELECT @end=PATINDEX('%[A-Za-z0-9@+.e][^A-Za-z0-9@+.e]%', @Contents+' ' collate SQL_Latin1_General_CP850_Bin) + 1
--include negative values|start
--SELECT @start=PATINDEX('%[^A-Za-z0-9@+.e][A-Za-z0-9@+.e]%', ' ' + @contents collate SQL_Latin1_General_CP850_Bin)
SELECT @start=PATINDEX('%[^A-Za-z0-9@+.e][A-Za-z0-9@+.e][^-?[0-9]\d*(\.\d+)?$]%', ' ' + @contents collate SQL_Latin1_General_CP850_Bin)
--include negative values|end
--for debugging|start
--SELECT [@value] = @value, [@Contents] = @Contents, [@start] = @start
--for debugging|end
--select @start,@end, LEN(@contents+'|'), @contents
SELECT @Value=RTRIM(SUBSTRING(@contents, @start, @End-@Start)),
@Contents=RIGHT(@contents+' ', LEN(@contents+'|')-@end)
IF SUBSTRING(@value, 1, 7)='@object'
INSERT INTO @objJSONTable (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 8, 5), SUBSTRING(@value, 8, 5), 'object'
ELSE
IF SUBSTRING(@value, 1, 6)='@array'
INSERT INTO @objJSONTable (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 7, 5), SUBSTRING(@value, 7, 5), 'array'
ELSE
IF SUBSTRING(@value, 1, 7)='@string'
INSERT INTO @objJSONTable (NAME, SequenceNo, parent_ID, StringValue, ValueType)
SELECT @name, @SequenceNo, @parent_ID, stringvalue, 'string'
FROM @strings
WHERE string_id=SUBSTRING(@value, 8, 5)
ELSE
IF @value IN ('true', 'false')
INSERT INTO @objJSONTable (NAME, SequenceNo, parent_ID, StringValue, ValueType)
SELECT @name, @SequenceNo, @parent_ID, @value, 'boolean'
ELSE
IF @value='null'
INSERT INTO @objJSONTable (NAME, SequenceNo, parent_ID, StringValue, ValueType)
SELECT @name, @SequenceNo, @parent_ID, @value, 'null'
ELSE
IF PATINDEX('%[^0-9]%', @value collate SQL_Latin1_General_CP850_Bin)>0
--BEGIN
INSERT INTO @objJSONTable (NAME, SequenceNo, parent_ID, StringValue, ValueType)
SELECT @name, @SequenceNo, @parent_ID, @value, 'real'
--for debugging|start
--SELECT [@value] = @value, [@Contents] = @Contents
--for debugging|end
--END
ELSE
INSERT INTO @objJSONTable (NAME, SequenceNo, parent_ID, StringValue, ValueType)
SELECT @name, @SequenceNo, @parent_ID, @value, 'int'
IF @Contents=' ' SELECT @SequenceNo=0
END
END
INSERT INTO @objJSONTable (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType)
SELECT '-',1, NULL, '', @parent_id-1, @type
--for debugging|start
--SELECT 'R E T U R N', * FROM @objJSONTable
--for debugging|end
DELETE h
FROM @objJSONTable h
WHERE h.NAME = '-'
--for debugging|start
--SELECT 'after delete', * FROM @objJSONTable
--for debugging|end
--SELECT *
--INTO #tbl
--FROM dbo.udfSplitString(@strColumnList)
SELECT ID = t.NAME
INTO #tbl
FROM @objJSONTable t
--for debugging|start
--SELECT '#tbl', t.* FROM #tbl t
--for debugging|end
DECLARE @strCurrentColumn VARCHAR(100)
, @strSQLColumn VARCHAR(1000)
--, @strSQL VARCHAR(2000) = 'SELECT * FROM (SELECT h.NAME, h.StringValue FROM @objJSONTable h) a PIVOT(MAX(StringValue) FOR NAME IN (*columnNamesHere*)) AS p'
, @strSQL NVARCHAR(MAX) = 'SELECT * FROM (SELECT h.NAME, h.StringValue FROM @objJSONTable h) a PIVOT(MAX(StringValue) FOR NAME IN (*columnNamesHere*)) AS p'
--for debugging|start
--SELECT [@strSQL] = @strSQL
--for debugging|end
SELECT TOP 1 @strCurrentColumn = t.ID
FROM #tbl t
WHILE @@ROWCOUNT > 0
BEGIN
--for debugging|start
--SELECT CONCAT('loop all columns >>> ', @strCurrentColumn)
--for debugging|end
SET @strSQLColumn = CONCAT(@strSQLColumn, '[', @strCurrentColumn, '], ')
DELETE #tbl
WHERE ID = @strCurrentColumn
SELECT TOP 1 @strCurrentColumn = t.ID
FROM #tbl t
END --WHILE @@ROWCOUNT > 0
SET @strSQLColumn = LEFT(@strSQLColumn, LEN(@strSQLColumn) - 1)
SET @strSQL = REPLACE(@strSQL, '*columnNamesHere*', @strSQLColumn)
--for debugging|start
--SELECT [@strSQLColumn] = @strSQLColumn, [@strSQL] = @strSQL
DROP TABLE #tbl
--for debugging|end
DECLARE @strParmDefinition NVARCHAR(500)
SET @strParmDefinition = N'@objJSONTable typHierarchy READONLY'
EXEC sys.sp_executesql @strSQL, @strParmDefinition
, @objJSONTable = @objJSONTable
答案 1 :(得分:0)
您正在寻找的签名应为:
<ScriptMethod> _
<WebMethod()> _
Public Function DailyCheckDealer(dealers As String()()) As String
' insert to db here
Return String.Empty
End Function
然而,通常最好使用强类型对象而不是数组。
<script>
var dealers = new Array();
dealers.push({ ID: "123", Phone: "870503-23-5370", Code: "021"));
...
</script>
VB代码:
Public Class Dealer
Public Property ID() As String
Get
Return m_ID
End Get
Set
m_ID = Value
End Set
End Property
Private m_ID As String
Public Property Code() As String
Get
Return m_Code
End Get
Set
m_Code = Value
End Set
End Property
Private m_Code As String
Public Property Phone() As String
Get
Return m_Phone
End Get
Set
m_Phone = Value
End Set
End Property
Private m_Phone As String
End Class
<WebService> _
<ScriptService> _
Public Class Service1
Inherits System.Web.Services.WebService
<ScriptMethod> _
<WebMethod> _
Public Function DailyCheckDealer(dealers As Dealer()) As String
' insert to db here
Return String.Empty
End Function
End Class
现在Web服务已经过时了 - 如果你能推荐创建WEB API控制器(http://docs.telerik.com/data-access/quick-start-scenarios/asp.net-web-api/quickstart-webapi-create-api-controllers),或者你坚持使用.NET 3.5框架WCF服务。