i’d like to know why this class doesn’t work, but if this piece of code is written in the aspx page directly, it works.
I want this in a class because is called several times in several pages to check if the user is already counted as visitor.
The principal idea of this is to count the number of users that are seeing my website.
The error is this:
Incorrect syntax near ‘:’
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near ‘:’.
THIS IS THE CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Data;
using System.Text;
namespace Project
{
public class ipAddress
{
SQL com = new SQL(); //Class to make SQL connection and do querys
public void GetPublicIP()
{
WebClient web = new WebClient();
System.IO.Stream stream = web.OpenRead(url);
string text = "";
using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
{
text = reader.ReadToEnd();
reader.Close();
}
string results = "";
try
{
foreach (DataRow item in com.Execute("select * from table where ip = '" + text + "' and data = '" + DateTime.Now.ToShortDateString() + "';").Rows)
{
results = item["ip"].ToString();
}
if (results == "")
{
com.FazerComando("insert into table (ip, date) values ('" + text + "', '" + DateTime.Now.ToShortDateString() + "');");
}
}
catch { }
}
}
}
Regards…
Well we don’t know what this
SQLclass is, but it looks like you’re injecting values directly into SQL, which is a very bad idea. It invites SQL injection attacks, mixes code and data, and makes conversions around numbers and date/time values much harder than they need to be. (In this particular case, you’re lucky – the string you’re building is just invalid SQL. It’s not, say, wiping out your database.)Instead, you should be using parameterized SQL where you include “placeholders” in the SQL itself, and provide the values separately.
Assuming
SQLis your own class, you should give it the facility to use parameterized SQL. SeeSqlCommand.Parametersfor an example.