Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 这是在bottonClick事件中编写的正确SQL代码吗?_C#_Sql - Fatal编程技术网

C# 这是在bottonClick事件中编写的正确SQL代码吗?

C# 这是在bottonClick事件中编写的正确SQL代码吗?,c#,sql,C#,Sql,我是ADO.NET数据库的新手,需要在bottonclick事件中添加sql选择代码 是否正确?更正select命令: cmd.CommandText = "SELECT * From Employee" 我建议您将代码附加到表单的加载事件。试试这个 string sql = "SELECT* From Employee where EmployeeId = @EmployeeId"; try { using (SqlConne

我是ADO.NET数据库的新手,需要在bottonclick事件中添加sql选择代码


是否正确?

更正select命令:

cmd.CommandText = "SELECT * From Employee"

我建议您将代码附加到表单的加载事件。

试试这个

     string sql = "SELECT* From Employee where EmployeeId = @EmployeeId";
        try
        {
            using (SqlConnection connection = new SqlConnection(cnStr))
            {
                connection.Open;
                using (SqlCommand command = new SqlCommand(sql, connection))
                {

                    command.Parameters.AddWithValue("EmployeeId", TxtId.Text);
                    command.ExecuteNonQuery();
                    Form1_Load(sender, e);
                }
                connection.Close;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

首先,看起来你少了一个名字。第二,您应该真正使用sql参数,而不是串联,这样您就不必担心清理输入,因为简单的替换并没有完全覆盖这些输入。最后,对于查询,您需要执行ExecuteReader,然后在中读取结果并对其执行操作ExecuteOnQuery用于删除、插入或更新等操作,和读者一起使用语句,以便正确处理它们。我似乎也忘记了在其中添加员工ID从员工中选择Eployee ID。我是否仍然需要使用文本。替换??感谢您回答我的问题,非常感谢它在new SqlCommandsql中说了连接这个词,连接在当前上下文中不存在,我应该怎么做?它应该可以工作。以前的代码有一些问题。你能试一下编辑好的吗。这对我来说很好
     string sql = "SELECT* From Employee where EmployeeId = @EmployeeId";
        try
        {
            using (SqlConnection connection = new SqlConnection(cnStr))
            {
                connection.Open;
                using (SqlCommand command = new SqlCommand(sql, connection))
                {

                    command.Parameters.AddWithValue("EmployeeId", TxtId.Text);
                    command.ExecuteNonQuery();
                    Form1_Load(sender, e);
                }
                connection.Close;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }