SQL Server实现参数化增删改查Class类

目录

SqlServerDatabase.Class

Main调用


SqlServerDatabase.Class

using System;
using System.Data;
using System.Data.SqlClient;

class SqlServerDatabase
{
    private readonly string connectionString;

    public SqlServerDatabase(string connectionString)
    {
        this.connectionString = connectionString;
    }

    public DataTable ExecuteQuery(string query, SqlParameter[] parameters = null)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            using (SqlCommand command = new SqlCommand(query, connection))
            {
                if (parameters != null)
                {
                    command.Parameters.AddRange(parameters);
                }

                SqlDataAdapter adapter = new SqlDataAdapter(command);
                DataTable dataTable = new DataTable();
                adapter.Fill(dataTable);

                return dataTable;
            }
        }
    }

    public int ExecuteNonQuery(string query, SqlParameter[] parameters = null)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            using (SqlCommand command = new SqlCommand(query, connection))
            {
                if (parameters != null)
                {
                    command.Parameters.AddRange(parameters);
                }

                return command.ExecuteNonQuery();
            }
        }
    }
}
 

Main调用

class Program
{
    static void Main()
    {
        string connectionString = "your_connection_string";
        SqlServerDatabase database = new SqlServerDatabase(connectionString);

        // 查询示例
        string selectQuery = "SELECT * FROM YourTable WHERE ColumnName = @Param";
        SqlParameter[] selectParameters = { new SqlParameter("@Param", "some_value") };
        DataTable result = database.ExecuteQuery(selectQuery, selectParameters);

        // 增加/删除/修改示例
        string updateQuery = "UPDATE YourTable SET Column1 = @Value WHERE Column2 = @Condition";
        SqlParameter[] updateParameters = { new SqlParameter("@Value", "new_value"), new SqlParameter("@Condition", "condition_value") };
        int rowsAffected = database.ExecuteNonQuery(updateQuery, updateParameters);
    }
}
 

你可能感兴趣的:(服务器,数据库)