【问题标题】:Fetching data from SQL Server 2005 using c#使用 c# 从 SQL Server 2005 获取数据
【发布时间】:2012-07-14 10:42:16
【问题描述】:

当其他两列的值相等时,我想从表中检索特定列。我的代码如下。四列是id,destination,source,price

我想在目的地和来源相等时显示价格。

你能帮帮我吗?

private void button1_Click(object sender, EventArgs e)
{

        SqlConnection con = new SqlConnection("Data source=.;initial catalog=loki;integrated security=true");
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter();

        DataTable dt = new DataTable();
        da.SelectCommand = new SqlCommand("select  price from metro where source='" + textBox1.Text + "' and destination='" + textBox2.Text + "'", con);
        da.Fill(dt);
        for(int i=0;i<dt.Rows.Count;i++)
        {
            textBox3.Text = dt.Rows[0][3].Count.ToString();
        }
    }

【问题讨论】:

  • 我对你为什么包含 textBox1 和 2 感到有些困惑。如果你想测试源和目标是否相等,我认为查询应该是:SELECT price FROM metro WHERE source=destination
  • 请使用参数化查询(或者更好,stored procedures)。使用字符串连接来构建 SQL 命令只是要求SQL injection attack
  • david hyogo....来源和目的地是两个不同的输入......这就是为什么我必须采取不同的......

标签: c# tsql sql-server-2005


【解决方案1】:

我觉得你在这之后......

    private void button1_Click(object sender, EventArgs e)
    {
        using (SqlConnection con = new SqlConnection("Data source=.;initial catalog=loki;integrated security=true"))
        {
            string query = "select  price from metro where source= @Source and destination = @Destination";

            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                cmd.Parameters.AddWithValue("@Source", textBox1.Text);
                cmd.Parameters.AddWithValue("@Destination", textBox2.Text);

                con.Open();
                object o  = cmd.ExecuteScalar();
                if(o != null && o != DBNull.Value)
                {
                   string price = (string) o; //please cast the return type as required
                   textBox3.Text = price;
                }
                con.Close();
            }
        }
    }

【讨论】:

  • 他们的错误是指定的强制转换无效“int price = (Int32) cmd.ExecuteScalar();”
  • 我举了一个例子,如果你的返回类型是十进制,那么请把它转换成十进制
  • 请查看我已处理的更新代码 cmd.ExecuteScalar()
  • 这一串价格=(string)o;
  • 好的好的,我明白了,但错误仍然是他们的.....无法将类型 int 完全转换为字符串
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-06
相关资源
最近更新 更多