gpt4 book ai didi

c# - 如果我在单独的文件中使用连接类,ADO.NET 如何添加参数?

转载 作者:行者123 更新时间:2023-11-30 21:07:04 25 4
gpt4 key购买 nike

如果我在单独的文件中使用类,ADO.NET 如何添加参数?

类:

class SQLconnect
{
public static void Sql(string Command_Text)
{
string connectionPath =
"Data Source=USER\\SQLEXPRESS;Initial Catalog=db;Integrated Security=SSPI;";

SqlConnection Connection = new SqlConnection(connectionPath);

Connection.Open();

SqlCommand Command = Connection.CreateCommand();
Command.CommandText = Command_Text;
Command.ExecuteNonQuery();

Connection.Close();
}
}

参数:

        SQLconnect.Sql("INSERT INTO [dbo].[work] ([name],[code])VALUES(@name, @code)");

SqlParameter param = new SqlParameter();
param.ParameterName = "@name";
param.Value = nameTextBox.Text;
param.SqlDbType = SqlDbType.Text;
// Parameters.Add(param);


param = new SqlParameter();
param.ParameterName = "@code";
param.Value = codeTextBox.Text;
param.SqlDbType = SqlDbType.Text;
// Parameters.Add(param);

最佳答案

一个选项是更新您的 SqlConnect.Sql() 方法以接受一组参数:

class SQLconnect
{
public static void Sql(string Command_Text, params SqlParameter[] parameters)
{
string connectionPath =
"Data Source=USER\\SQLEXPRESS;Initial Catalog=db;Integrated Security=SSPI;";

SqlConnection Connection = new SqlConnection(connectionPath);

Connection.Open();

SqlCommand Command = Connection.CreateCommand();
Command.CommandText = Command_Text;

if(parameters != null && parameters.Length > 0)
{
foreach(var p in parameters)
Command.Parameters.Add(p);
}


Command.ExecuteNonQuery();

Connection.Close();
}
}

那么你的调用代码应该是这样的:

    SqlParameter param1 = new SqlParameter();
param1.ParameterName = "@name";
param1.Value = nameTextBox.Text;
param1.SqlDbType = SqlDbType.Text;

param2 = new SqlParameter();
param2.ParameterName = "@code";
param2.Value = codeTextBox.Text;
param2.SqlDbType = SqlDbType.Text;

SQLconnect.Sql("INSERT INTO [dbo].[work] ([name],[code])VALUES(@name, @code)", param1, param2);

关于c# - 如果我在单独的文件中使用连接类,ADO.NET 如何添加参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10718822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com