I'm trying with C# to read data from XML file, and update my SQL table with. But nothing happens.
My XML look like this
<User>
<Table>
<userID>535631</userID>
<Date>2017-12-18</Date>
</Table>
<Table>
<userID>36334</userID>
<Date>2020-02-03</Date>
</Table>
<Table>
<userID>734563</userID>
<Date>2020-02-03</Date>
</Table>
<Table>
<userID>6334</userID>
<Date>2020-02-21</Date>
</Table>
</User>
And what I tried:
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\\temp\\data\\myData.xml");
XmlNodeList node = doc.SelectNodes("/User/Table");
string source = ConfigurationManager.ConnectionStrings["JBVRM"].ConnectionString;
SqlConnection conn = new SqlConnection(source);
SqlCommand cmd = new SqlCommand();
foreach (XmlNode xn in node)
{
string userID = xn["userID"].InnerText;
string NewDate= xn["Date"].InnerText;
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter("UPDATE [dbo].[User] SET Date='"+NewDate+"' WHERE UserID="+ userID , source);
conn.Close();
// Console.WriteLine(userID+" "+Date); // This prints everything very fine.
}
Any suggestions what I'm doing wrong? I can print date and userID fint. but my table is not being updated.
SOLUTION Thanks to @Magnetron and @Gnud
using (SqlConnection connection = new SqlConnection(source))
{
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "UPDATE [dbo].[User] SET Date=@Date WHERE userID=@userID";
cmd.Parameters.AddWithValue("@Date", xn["Date"].InnerText);
cmd.Parameters.AddWithValue("@userID", xn["userID"].InnerText);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
SqlAdapterConstructor, you're using is for a select command not a update one.CommandTextand parameters, instead of trusting the user input, as this make you vulnerable for sql injection.using(of the connection) outside the loop. AndOpen()the connection before the loop. Only connect once. If you create and close the connection inside the loop, you will connect and disconnect once for every row in the XML file.