0

这是我的代码:

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)();

他们的意思有什么帮助吗?我不太确定我做错了什么。

4

3 回答 3

5

Your statement:

SqlCommand cmd = new SqlCommand

should be :

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

Later when you are opening and closing the connection, just remove the parameters, these parameters are required for SqlCommand constructor.

You may have your code like:

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
}

Read about basic C#, constructors and ADO.Net Examples on MSDN

于 2013-11-04T14:31:51.430 回答
4

C# 不是你需要让你的意图知道的红宝石。实例化对象有 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 。

于 2013-11-04T14:36:30.827 回答
1

You haven't correctly created your SqlCommand instance:

SqlCommand cmd = new SqlCommand

turns into:

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

which in turn means:

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

becomes simply:

con.Open();

and similarly with con.Close();.

于 2013-11-04T14:32:06.053 回答