如何在c#中将值传递给sql命令

时间:2014-06-02 08:15:10

标签: c# sql sql-server

我有一个SQL命令:

string keyProcesses = "SELECT distinct STUFF((SELECT ', '+ cn.name  from WMCCMCategories cn  INNER JOIN CategorySets uc ON uc.categoryId = cn.categoryID INNER JOIN KeyProcesses u ON u.categorySetId = uc.setId  INNER JOIN Companies c ON c.companyId = u.companyId  WHERE c.companyName = @companyName  ORDER BY cn.name FOR XML PATH('')), 1, 1, '') AS listStr FROM WMCCMCategories cnn Group by cnn.name";

我有:

public SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandText = commandText; //where commandText is another SQL statement
sqlCmd.Parameters.Clear();

然后我执行连接:

string connectionString = ConfigurationSettings.AppSettings["connectionString"];
using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(commandText, connection);
    try
    {
        connection.Open();
        SqlDataAdapter sdr = new SqlDataAdapter(sqlCmd.CommandText, connection);
        DataTable dt=new DataTable();
        sdr.Fill(dt)

之后我想转到下一个SQL命令并向该命令添加参数:

sqlCmd.CommandText = keyProcesses;
sqlCmd.Parameters.AddWithValue("@companyName", compnyName);
SqlDataAdapter sdr1 = new SqlDataAdapter(sqlCmd.CommandText, connection);
DataTable dtb1 = new DataTable();
sdr1.Fill(dtb1);

但它无法执行此SqlCommand。我已经确保SQL密钥进程可以在预先添加的修复参数的情况下正常运行。compnName不为空。这里唯一的疑问是如何为sql参数添加值。我不知道我使用它的方式有什么问题?

编辑:我更新了整个代码部分,以便于调查问题:

string connectionString = ConfigurationSettings.AppSettings["connectionString"];
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = new SqlCommand(commandText, connection);

                try
                {
                    connection.Open();

                    SqlDataAdapter sdr = new SqlDataAdapter(sqlCmd.CommandText, connection);
                    DataTable dt=new DataTable();
                    sdr.Fill(dt);
                        //To store the values of company names:
                    List<CompanyModel> companies = new List<CompanyModel>();


                        for(int i = 0; i < dt.Rows.Count; i++)
                        {
                            companies.Add(new CompanyModel 
                            { 
                                compnSN = i + 1,
                                compnName =  dt.Rows[i]["companyName"].ToString(),
                                compnAddress =  dt.Rows[i]["address"].ToString()
                            });
                        }

                        companyRepeater.DataSource = companies;
                        companyRepeater.DataBind();

                        string comName = dt.Rows[0]["companyName"].ToString();
                        var names = companies.Select(c => c.compnName);

                        string[] arr = names.ToArray();
                        foreach (string compnyName in arr)
                        {
                            //To write names to file for debugging purpose
                            using (StreamWriter _testData = new StreamWriter(Server.MapPath("~/File.txt"), true))
                            {

                                _testData.WriteLine(compnyName); // Write the file.
                            }


                              //Get KeyProcesses
                              sqlCmd.CommandText = keyProcesses;
                              //sqlCmd.Parameters.AddWithValue("@companyName", compnyName);
                              sqlCmd.Parameters.Add("@companyName", SqlDbType.NVarChar);
                              sqlCmd.Parameters["@companyName"].Value = compnyName;
                             // SqlDataAdapter sdr1 = new SqlDataAdapter(sqlCmd.CommandText, connection);
                              DataTable dtb1 = new DataTable();
                              //sdr1.Fill(dtb1);
                              using (var reader = sqlCmd.ExecuteReader())
                              {
                                  dtb1.Load(reader);
                              }

                              companies.Add(new CompanyModel
                              {
                                  compnKeyProcesses = dtb1.Rows[0][0].ToString()

                              });

2 个答案:

答案 0 :(得分:1)

坦率地说,你根本不需要适配器。它只会增加混乱。删除它:

sqlCmd.CommandText = keyProcesses;
sqlCmd.Parameters.AddWithValue("@companyName", compnyName);
using(var reader = sqlCmd.ExecuteReader()) {
    dtb1.Load(reader);
}

答案 1 :(得分:0)

sqlCmd.Parameters.Add(&#34; @ companyName&#34;,SqlDbType.NVarchar(1000)); //或者你的任何类型                                                                      

数据库列

sqlCmd.Parameters [&#34; @ companyName&#34;]。Value = compnyName;

这是一种更安全的方式,可能有所帮助