在(connectionString)上有一个错误的红色下划线,表示当前上下文中不存在名称'ConnectionString'。 在使用using语句之前,我是否需要声明?
SqlConnection conn = new SqlConnection("Data Source=baaa;Initial Catalog=InventorySystem;Integrated Security=True") ;
using (SqlConnection connection = new SqlConnection(connectionString)
{
connection.Open();
using (SqlCommand command = new SqlCommand(
"SELECT product.P_ID, Product.P_Name,Product.Leadtime, Product.SafetyStockamount," +
"Monthlysales.Month, Monthlysales.totalsalesamount, (totalsalesamount/30) as Averagedailysales, ((totalsalesamount/30) * Leadtime + SafetyStockamount) as reorderpoint " +
"FROM Product, Monthlysales " +
"where Product.P_ID = Monthlysales.P_ID AND Product.P_ID =@P_ID AND Monthlysales.Month =@Month ", connection))
{
command.Parameters.Add(new SqlParameter("P_ID", pid));
command.Parameters.Add(new SqlParameter("Month", Startmonth));
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
adapter.Fill(ds);
// now you have the data in Dataset ds
}
答案 0 :(得分:2)
在using
语句中,您希望获得connectionString
的值。但是没有任何变数。
更改
SqlConnection conn = new SqlConnection("Data Source=baaa;Initial Catalog=InventorySystem;Integrated Security=True") ;
到
string connectionString= "Data Source=baaa;Initial Catalog=InventorySystem;Integrated Security=True";
此外,您还没有在using
声明中结束括号。
using (SqlConnection connection = new SqlConnection(connectionString))
答案 1 :(得分:0)
如果您完全确定您的connectionString,请使用以下代码:
using (SqlConnection connection = new SqlConnection("Data Source=baaa;Initial Catalog=InventorySystem;Integrated Security=True"))
{
connection.Open();
using (SqlCommand command = new SqlCommand(
"SELECT product.P_ID, Product.P_Name,Product.Leadtime, Product.SafetyStockamount," +
"Monthlysales.Month, Monthlysales.totalsalesamount, (totalsalesamount/30) as Averagedailysales, ((totalsalesamount/30) * Leadtime + SafetyStockamount) as reorderpoint " +
"FROM Product, Monthlysales " +
"where Product.P_ID = Monthlysales.P_ID AND Product.P_ID =@P_ID AND Monthlysales.Month =@Month ", connection))
{
command.Parameters.Add(new SqlParameter("P_ID", pid));
command.Parameters.Add(new SqlParameter("Month", Startmonth));
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
adapter.Fill(ds);
}
}
答案 2 :(得分:0)
作为您的代码
SqlConnection conn = new SqlConnection("Data Source=baaa;Initial Catalog=InventorySystem;Integrated Security=True") ;
您正在创建不是连接字符串的连接实例。使它成为String connectionString
并将它们作为参数传递给SqlConnection。