在WPF应用程序中执行INSERT查询时出现SqlCommand方法错误

时间:2012-02-06 19:19:43

标签: c# wpf visual-studio-2010 sql-server-2008

我正在使用C#编写WPF应用程序。数据库是SQL Server 2008.我在数据库中有一个表“Employee”,我需要在其中插入一行。我已成功连接数据库,但当我尝试执行此行时:

cmd = new SqlCommand(cmdText, conn);

出现此错误:“System.Data.SqlClient.SqlCommand.SqlCommand(String,System.Data.SqlClient.SqlConnection)”的最佳重载方法匹配包含一些无效参数。

这是我的代码:

private void addbtn_Click(object sender, RoutedEventArgs e)
    {
        //FUNCTION TO ADD NEW EMPLOYEE RECORD IN DATABASE
        try
        {
            conn.ConnectionString = "Data Source=AZEEMPC;" + "Initial Catalog=IEPL_Attendance_DB;";
            conn.Open();
            cmdText = "INSERT INTO Employee VALUES ('" + strCurrentString + "','" + emp_name.Text + "')";
            cmd = new SqlCommand(cmdText, conn);
            data_ad = new SqlDataAdapter(cmd);
            data = new DataSet();
            data_ad.Fill(data);
            MessageBox.Show("Record Inserted Successfully!");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

有什么建议吗?

1 个答案:

答案 0 :(得分:3)

conn必须属于SqlConnection类型 - 您能确认它是吗?

SqlConnection conn;

因为它是本机SQL Server连接,所以您不需要在连接字符串中传递驱动程序名称。

conn.ConnectionString = "Server=AZEEMPC;Database=IEPL_Attendance_DB;Trusted_Connection=true;";