已引用System.Data.SqlClient,C#仍无法识别SqlConnection求助
Hey there, let's work through this SqlConnection error you're seeing—even with the using System.Data.SqlClient; directive in place, there are a few common gotchas in Visual Studio that might be causing this. Here's what to check step by step:
Verify you've added the correct reference/NuGet package
- For .NET Framework projects:
SqlConnectionlives in theSystem.Dataassembly. Right-click your project in Solution Explorer → select Add → Reference → go to the Assemblies tab, findSystem.Data, check the box next to it, and click OK. - For .NET Core/.NET 5+ projects: The old
System.Data.SqlClientnamespace has been moved to a NuGet package. Right-click your project → select Manage NuGet Packages → go to the Browse tab, search forMicrosoft.Data.SqlClient, install the latest stable version. After installing, you can either useusing Microsoft.Data.SqlClient;(the modern recommended namespace) or keepusing System.Data.SqlClient;(most versions still support this for compatibility).
- For .NET Framework projects:
Check your project's target framework
Make sure your project is targeting a framework version that supportsSqlConnection. Right-click your project → Properties → go to the Application tab, check the Target framework dropdown. For .NET Framework, aim for 4.6.1 or newer; for .NET Core/.NET, 3.1 or newer works best.Clean and rebuild your solution
Visual Studio's build cache can sometimes cause false errors. Go to the top menu → Build → Clean Solution, then Build → Rebuild Solution. If that doesn't help, try restarting Visual Studio entirely to clear any cached issues.Quick note on your code
Also, a small side issue: your entry point method should beMain(capital M) instead ofmain—C# is case-sensitive, sopublic static void Main()is required for the program to run correctly once you fix the SqlConnection error.
内容的提问来源于stack exchange,提问作者user9758771

