当我尝试运行此代码时,出现错误:
' ='
附近的语法不正确
你能否帮我纠正这个错误。
String sDate = DateTime.Now.ToString();
DateTime datevalue = (Convert.ToDateTime(sDate.ToString()));
String dy = datevalue.Day.ToString();
int mn = datevalue.Month;
int yy = datevalue.Year;
var debit = _dbConnect.GetOneData("SELECT SUM(debit) FROM [sem_db].[dbo].[ledger] WHERE h_id = '9' & entry_date.Value.Month = 'mn' && entry_date.Value.Year = 'yy'");
public class DbConnect
{
readonly SqlConnection _con = new SqlConnection();
private void GetConnection()
{
_con.ConnectionString = ConfigurationManager.ConnectionStrings["sem_dbConnectionString"].ConnectionString;
_con.Open();
return;
}
public object GetOneData(string query)
{
GetConnection();
var cmd = new SqlCommand(query, _con);
var val = cmd.ExecuteScalar(); ------------>(error comes here)
_con.Close();
return val;
}
}
答案 0 :(得分:2)
在sql中,运算符是'和'不是'&&' 假设你是usinc C#代码 变化
var debit = _dbConnect.GetOneData("SELECT SUM(debit) FROM [sem_db].[dbo].[ledger] WHERE h_id = '9' & entry_date.Value.Month = 'mn' && entry_date.Value.Year = 'yy'")
到
var debit = _dbConnect.GetOneData("SELECT SUM(debit) FROM [sem_db].[dbo].[ledger] WHERE h_id = '9' and [ledger].Month = '"+mn+"' and [ledger].Year = '"+yy+"'")
尝试使用参数化查询来避免SQL注入
答案 1 :(得分:1)
var debit = _dbConnect.GetOneData("SELECT SUM(debit) FROM [sem_db].[dbo].[ledger] WHERE h_id = '9' & entry_date.Value.Month = 'mn' && entry_date.Value.Year = 'yy'")
答案 2 :(得分:0)
var debit = _dbConnect.GetData_DataTable("select (sum(debit)-sum(credit)) as openingBalance from ledger where h_id='9' and cast( entry_date as date)< CAST( dateadd(MONTH ,-1, GETDATE())as date)");