我想知道为什么这个类不起作用,但是如果这段代码直接写在aspx页面中,它就起作用了。 我想在类里面使用它,因为在多个页面中多次调用它来检查用户是否已被计为访问者。 这样做的主要想法是统计浏览我网站的用户数量。
错误是这样的: “:”附近的语法不正确
描述:在执行当前网络请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其在代码中的来源的更多信息。
异常详细信息:System.Data.SqlClient.SqlException:“:”附近的语法不正确。
这是代码:
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 { }
}
}
}
问候...
最佳答案
好吧,我们不知道这个 SQL
类是什么,但看起来您正在将值直接注入(inject) SQL,这是一个非常糟糕的主意。它邀请SQL injection attacks ,混合代码和数据,并使围绕数字和日期/时间值的转换比他们需要的要难得多。 (在这种特殊情况下,您很幸运 - 您正在构建的字符串只是无效的 SQL。它不会,比如说,清除您的数据库。)
相反,您应该使用参数化 SQL,在 SQL 本身中包含“占位符”,并单独提供值。
假设 SQL
是您自己的类,您应该为它提供使用参数化 SQL 的便利。参见 SqlCommand.Parameters
举个例子。
关于c# - 未知错误 - 附近的语法不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11333460/