每次都会发生此错误。我该怎么办?

时间:2020-09-04 06:38:32

标签: c# sql sql-server ado.net

我已经开始从事现金券项目。当我单击“提交”按钮时,将出现一个弹出框,并显示“ Invalid Object voucher_table”。 我该怎么办?

private void bunifuFlatButton1_Click(object sender, EventArgs e)
    {
        string con = ConfigurationManager.ConnectionStrings["mydb"].ConnectionString;
        SqlConnection sqlcn = new SqlConnection(con);
        sqlcn.Open();

        try
        {
            SqlCommand cmd = new SqlCommand("INSERT INTO voucher_table(customerID, planName, days, planAmount, validFrom, validTo, amountInWords, date, rupees) values(@customerID, @planName, @days, @planAmount, @validFrom, @validTo, @amountInWords, @date, @rupees)", sqlcn);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@customerID", customerID.Text);
            cmd.Parameters.AddWithValue("@planName", planName.Text);
            cmd.Parameters.AddWithValue("@days", days.Text);
            cmd.Parameters.AddWithValue("@planAmount", planAmount.Text);
            cmd.Parameters.AddWithValue("@validFrom", validFrom.Text);
            cmd.Parameters.AddWithValue("@validTo", validTo.Text);
            cmd.Parameters.AddWithValue("@amountInWords", amountInWordsTextBox1.Text + amountInWordsTextBox2.Text);
            cmd.Parameters.AddWithValue("@date", date.Text);
            cmd.Parameters.AddWithValue("@rupees", rupees.Text);

            int i = cmd.ExecuteNonQuery();
            if (i > 0)
            {
                MessageBox.Show("Voucher Created Successfully");
                SqlCommand cmd1 = new SqlCommand("select max(primaryNo) from voucher_table", sqlcn);
                SqlDataReader dr1 = cmd1.ExecuteReader();
                if (dr1.Read())
                {
                    MessageBox.Show("Your Voucher No is '" + dr1.GetInt32(0) + "'Your Voucher is Created Successfully!");
                    Voucher_Successful success = new Voucher_Successful();
                    success.ShowDialog();
                }
                this.Close();
            }
            else
            {
                MessageBox.Show("An Error Occured... Voucher Not Created");
            }
            sqlcn.Close();
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message);
        }

编辑:Image 01

Image 02

编辑:找到的答案: 我添加了初始目录:我的现金券;在app.config中,问题已解决。

2 个答案:

答案 0 :(得分:0)

我认为您不在正确的数据库中(即,SQL命令找不到voucher_table)。 检查您所连接的数据库中是否确实存在voucher_table。

我发现了与您类似的问题,您也可能在那找到帮助:SQL Server: invalid object name in query execution

答案 1 :(得分:0)

我认为您的连接字符串中存在问题,因为错误消息明确提到找不到表名。有一种检查连接性的简单方法。只需执行以下操作

check connection string

无需添加连接,仅用于测试即可。测试完成后,单击“取消”按钮将其关闭。