【问题标题】:Select fields with SQL statement inside CommandText, c#在CommandText中选择带有SQL语句的字段,c#
【发布时间】:2016-06-17 05:01:09
【问题描述】:

所以我想从 2 个表中选择特定字段并将它们显示在 datagrid 中,所以我使用与 2 个表匹配的 ID 的内部联接,并且我想在 textbox 值时选择字段( txtTelephone) 等于我表中的一个数字。

这是我的代码:

    private void buttonSearch_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("*some connection info*");
        con.Open();
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "from C in Contact join P in Phones on C.[ID Επαφής] equals P.[ID Επαφής] where (P.Αριθμός = ('"+txtTelephone.Text+"')) select new {C.Επώνυμο, C.Όνομα, C.[Ημ. Γέννησης], P.[Περιγραφή Τηλεφώνου], P.Αριθμός}";
        cmd.ExecuteNonQuery();
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        dataGridView1.DataSource = dt;

        con.Close();
    }

【问题讨论】:

  • 我认为您可能将linqsql 混合在一起——您的commandtext 应该是select 声明...
  • SqlConnection、SqlCommand 等...仅适用于 MS SQL Server,不是吗?

标签: c# mysql sql-server winforms


【解决方案1】:

您的CommandText需要类似的 SQL 语句

cmd.CommandText = "SELECT FROM table WHERE id = @PAR"

您还应该考虑使用SQlCommand.ParameterstxtTelephone.Text 传递给您的查询。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    相关资源
    最近更新 更多