添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Home
C#
SqlParameter Example
This page was last reviewed on Nov 17, 2022.
Dot Net Perls
SqlParameter. This C# class makes SQL queries easier to build. It is part of the System.Data.SqlClient namespace. It is an easy way to parameterize queries.
SqlClient
Constructor notes. SqlParameter has several overloaded constructors. For many simple uses, we can just invoke the 2-argument SqlParameter constructor.
An example. Here we see the simplest overload of the SqlParameter instance constructor and adds it to the SqlCommand type's Parameter collection. There are other ways to add parameters.
SqlCommand
Here The most important thing is the principle of parameterized queries when using SQL databases.
Info Many System.Data objects can be wrapped in "using" statements to ensure the best cleanup of their resources.
using
Detail Here the string "Fido" is specified to match the Name column in the Dogs1 table.
using System; using System.Data.SqlClient; class Program static void Main() // The name we are trying to match. string dogName = "Fido" ; // Use preset string for connection and open it. string connectionString = ConsoleApplication1.Properties.Settings.Default.ConnectionString; using (SqlConnection connection = new SqlConnection(connectionString)) connection.Open(); // Description of SQL command: // 1. It selects all cells from rows matching the name. // 2. It uses LIKE operator because Name is a Text field. // 3. @Name must be added as a new SqlParameter. using (SqlCommand command = new SqlCommand( "SELECT * FROM Dogs1 WHERE Name LIKE @Name" , connection)) // Add new SqlParameter to the command. command.Parameters.Add(new SqlParameter( "Name" , dogName)); // Read in the SELECT results. SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) int weight = reader.GetInt32(0); string name = reader.GetString(1); string breed = reader.GetString(2);