I'm writing an app to store texts to an SQL database, but my code throws an exception saying "the variable name @par1 has already been declared", I'm not sure how to get this working and would like some help fixing this if possible please =]
offending code is below
private void SMSGetter()
{
try {
DecodedShortMessage[] messages = Comm.ReadMessages(PhoneMessageStatus.All, PhoneStorageType.Sim);
SqlConnection Conn = new SqlConnection("Data Source=*********;Initial Catalog=********;User ID=**********;Password=***********");
SqlCommand com = new SqlCommand();
com.Connection = Conn;
Conn.Open();
foreach (DecodedShortMessage message in messages)
{
//com.CommandText = ("INSERT INTO SMSArchives(Message,Blacklist) VALUES ('" + message.Data.UserDataText + "', 'Yes')");
//com.ExecuteNonQuery();
com.CommandText = ("INSERT INTO SMSArchives(Message,Blacklist) VALUES (@par1,@par2)");
com.Parameters.AddWithValue("@par1", message.Data.UserDataText);
com.Parameters.AddWithValue("@par2", "Yes");
com.ExecuteNonQuery();
}
Conn.Close();
}
catch (Exception ex) {
Log(ex.ToString());
}
}
You are using the same command for every iteration, but adding parameters each time. Try calling
com.Parameters.Clear();
at the end of each loop iteration. You could also pre-create the parameters and just set the .Value
per iteration - probably marginally faster.
Also: fix the SQL injection hole :)
private void SMSGetter()
{
Log("Getter Fired");
//var message = GSM.ReadMessage(4);
//GSM.ReadMessage(4);
//TcpClientChannel client = new TcpClientChannel();
//ChannelServices.RegisterChannel(client, false);
//string url = "*******";
//ISmsSender smssender = (ISmsSender)Activator.GetObject(typeof(ISmsSender), url);
try
{
DecodedShortMessage[] messages = Comm.ReadMessages(PhoneMessageStatus.All, PhoneStorageType.Sim);
SqlConnection Conn = new SqlConnection("Data Source=*********;Initial Catalog=********;User ID=**********;Password=***********");
SqlCommand com = new SqlCommand();
com.Connection = Conn;
Conn.Open();
com.CommandText = ("INSERT INTO SMSArchives(Message,Blacklist) VALUES (@par1,@par2)");
com.Parameters.Add("@par1");
com.Parameters.Add("@par2");
foreach (DecodedShortMessage message in messages)
{
com.Parameters["@par1"].value = message.Data.UserDataText;
com.Prepare(); //fix SQL injection :)
com.ExecuteNonQuery();
}
Conn.Close();
}
catch (Exception ex)
{
Log(ex.ToString());
}
}
You are adding the parameters at every iteration in foreach. Consider the following:
com.CommandText = ("INSERT INTO SMSArchives(Message,Blacklist) VALUES (@par1,@par2)");
command.Parameters.Add(new SqlParameter("@par1", ""));
com.Parameters.AddWithValue("@par2", "Yes");
foreach (DecodedShortMessage message in messages)
{
command.Parameters["@par1"].Value = message.Data.UserDataText;
com.ExecuteNonQuery();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.