SqlDataReader parameter not working

风格不统一 提交于 2019-12-31 07:42:48

问题


I have a windows form that I am asking a user to enter a pcname in textbox1 and then trying to use SqlDataReader to the read from the database to get the pc ipaddress and then map the pc drive to my local pc.

But for some reason when I use the textbox within the SQL parameter it's not working. But when I replace the textbox1.text with the actual pcname it works fine. Hopefully someone can help me find out why the parameter isn't working correctly.

Here is my code:

public void button1_Click(object sender, EventArgs e)
{
    string results = "";

    using (SqlConnection cs = new SqlConnection(@"***removed connection string***"))
    {
        cs.Open();

        string query = "select stationipaddress from station where stationname = @StationName";

        using (SqlCommand cmd = new SqlCommand(query, cs))
        {
            // Add the parameter and set its value -- 
            cmd.Parameters.AddWithValue("@StationName", textBox1.Text);

            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    label3.Text = dr.GetSqlValue(0).ToString();
                    results = dr.GetValue(0).ToString();
                    MessageBox.Show(dr.GetValue(0).ToString());
                    MessageBox.Show(results);
                }

                string myvar = string.Format(@"use S: \\" + label3.Text + "\\c$\logs 0A36303 /user:admin", label3.Text);

                Process p = new Process();
                p.StartInfo.FileName = "net.exe";
                p.StartInfo.Arguments = (myvar);
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.CreateNoWindow = true;
                p.Start();

回答1:


Maybe if you separate you code in different lines, one to set up your parameter, and one to add it, you can better see where the problem is. Something like this:

SqlParameter param1 = new SqlParameter("@StationName", SqlDbType.NVarChar, textBox1.Text.length);
param1.Value = textBox1.Text;
cmd.Parameters.Add(param1);

at least is easier to see what is going on on the debugger.



来源:https://stackoverflow.com/questions/13647964/sqldatareader-parameter-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!