不可调用成员SqlCommand不能像方法一样使用
c#
刚开始学习 C# 和 SQL Server。
在 Visual Studio 2019 中,我有以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace ConnectingToSQLServer
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Data Source=(LocalDb)MSSQLLOCALDB;Initial Catalog=EmployeesDb;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = SqlCommand()) // <- error is pointing here
{
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM Employees";
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
// int id = dr["id"]();
string FirstName = dr["FirstName"].ToString();
string LastName = dr["LastName"].ToString();
string email = dr["email"].ToString();
// int userlevel = dr["userlevel"].ToString();
Console.WriteLine(FirstName + " " + LastName);
}
dr.Close();
}
}
Console.ReadKey();
}
}
}
在输出中,我收到以下错误:
error CS1955: Non-invocable member 'SqlCommand' cannot be used like a method.
但我不知道为什么。
我做错了什么,我该如何解决?
回答
您会收到编译时错误,因为它SqlCommand是一个对象,您需要使用new关键字对其进行初始化。
using (SqlCommand cmd = new SqlCommand())
- 我认为最好将这篇文章作为错字关闭