我们使用以下代码示例通过存储过程 (SQL Server) 将数据从我的应用程序发送到外部数据库。
这里我还需要支持MySQL。因此,根据最终用户选择的数据库,我们需要将数据发送到 MySQL 或 SQL Server
C# 代码将在不同的计算机上运行,并且数据库服务器将是不同的服务器。
C# 代码
using (SqlConnection sqlConnection = new SqlConnection(<<MyConnectionString>>))
{
using (SqlCommand sqlCommand = new SqlCommand(<<StoredProcedureName>>, sqlConnection))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add("tblStudent", SqlDbType.Xml).Value = students.ToList().ToXML();
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
}
}
存储过程
CREATE PROCEDURE `usp_UpdateStudent` (@tblStudent XML)
BEGIN
SET NOCOUNT ON;
INSERT INTO Student(StudentId,StudentName)
SELECT Student.value('(StudentId)[1]', 'nvarchar(100)') as StudentId,
Student.value('(StudentName)[1]', 'nvarchar(100)') as StudentName
FROM
@tblStudent.nodes('/ArrayOfStudent/Student')AS TEMPTABLE(Student)
END
我在网上搜索了如何将 xml 字符串作为输入参数从 C# 传递到存储过程。但我没有得到任何具体答案。
请建议如何创建一个以 XML 作为输入参数的存储过程,以及如何将 XML 字符串从 C# 传递到该存储过程。
注意:以上代码在 SQL Server 中按预期工作。当我尝试使用 MySQL 实现相同的功能时,我发现 MySQL 不支持 xml 作为存储过程中的输入类型参数。看起来我需要将 xml 作为普通文本传递并解析存储过程中的文本。
如果有更有效的方法,请告诉我。
最佳答案
使用 Load_File() 将 xml 数据导入到本地变量中,而 ExtractValue() 然后使用 XPath 查询 XML 数据。例如,在下面的代码中,它从 xml_content 变量中检索学生计数:
declare xml_content text;
declare v_row_count int unsigned;
set xml_content = load_file(path);
set v_row_count = extractValue(xml_content, concat('count(', node, ')'))
路径:'C:\students1.xml',节点:'/student_list/student'
关于c# - 将 xml 字符串作为输入传递给 MySQL 存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43111355/