"A new expression requires (), [], or {} after type"是什么意思?



这是我的代码:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Data;
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = "Data Source=OCS-MXL930055N\;Initial           Catalog=sample;Integrated Security=True";
        SqlCommand cmd = new SqlCommand
        con.Open("Select * from ShoppingList", con);
        con.Close("Select * from ShoppingList", con);
    }
}

这些是我遇到问题的行:

con.Open("Select * from ShoppingList", con)();
con.Close("Select * from ShoppingList", con)();

对它们的含义有任何帮助吗?我不太确定我做错了什么。

您的陈述:

SqlCommand cmd = new SqlCommand

应该是 :

SqlCommand cmd = new SqlCommand("Select * from ShoppingList");

稍后在打开和关闭连接时,只需删除参数,这些参数是构造函数SqlCommand必需的。

您的代码可能如下所示:

using(SqlConnection con = new SqlConnection("Data Source=OCS-MXL930055N\;Initial Catalog=sample;Integrated Security=True"))
using(SqlCommand cmd = new SqlCommand("Select * from ShoppingList", con))
{
    //.. code to execute command
}

阅读有关 MSDN 上的基本 C#、构造函数和 ADO.Net 示例

的信息

C# 不是 ruby,你需要表达你的意图。有 3 种方法可以实例化对象,全部使用 new 运算符:例如

var myObj = new MyObj(); // call a constructor (parameterless)
var myObjArray = new MyObj[10]; // create an array of 10 MyObjs
var myObj = new MyObj{someProperty="someValue"}; // initializer notation.

请注意,您可以混合使用数组和初始值设定项,以便执行此操作及其法律:

var myInts = new int[]{1,2,3,4,5,6}; //create an int array with 6 values.

要修复您的代码段,您需要添加括号,如下所示:

   SqlCommand cmd = new SqlCommand();

如果您要发送SQL字符串,我强烈建议使用nuget上的Dapper-Dot-Net库。

您尚未正确创建SqlCommand实例:

SqlCommand cmd = new SqlCommand

变成:

SqlCommand cmd = new SqlCommand("Select * from ShoppingList");

这反过来意味着:

con.Open("Select * from ShoppingList", con)();

变得简单:

con.Open();

con.Close();类似.

相关内容

最新更新