【问题标题】:Pasting textbox values to access database粘贴文本框值以访问数据库
【发布时间】:2011-02-13 06:44:22
【问题描述】:

现在我在 try 语句中遇到了问题(int count =insert.......)。 编译器说(当我按下表单上的按钮以将值保存在文本框中)它无法将参数值从字符串转换为 Int32。 代码:

private void button1_Click(object sender, EventArgs e) {

       string conString = "Provider=Microsoft.Jet.OLEDB.4.0;"
     + "Data Source=C:\\Users\\Simon\\Desktop\\save.mdb";

        OleDbConnection empConnection = new OleDbConnection(conString);


        string insertStatement = "INSERT INTO obroki_save "
                             + "([ID_uporabnika],[datum],[ID_zivila],[skupaj_kalorij]) "
                             + "VALUES (@ID_uporabnika,@datum,@ID_zivila,@skupaj_kalorij)";

        OleDbCommand insertCommand = new OleDbCommand(insertStatement, empConnection);

        insertCommand.Parameters.Add("@ID_uporabnika", OleDbType.Integer).Value = users.iDTextBox.Text;
        insertCommand.Parameters.Add("@datum", OleDbType.Date).Value = DateTime.Now;
        insertCommand.Parameters.Add("@ID_zivila", OleDbType.Integer).Value = iDTextBox.Text;
        insertCommand.Parameters.Add("@skupaj_kalorij", OleDbType.Integer).Value = textBox1.Text;
        empConnection.Open();

        try
        {
           int count = insertCommand.ExecuteNonQuery();
        }
        catch (OleDbException ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            empConnection.Close();
            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();
            textBox4.Clear();
            textBox5.Clear();
        }
    }

【问题讨论】:

    标签: c# insert database-connection


    【解决方案1】:
    insertCommand.Parameters.Add("@datum", OleDbType.Char).Value = DateTime.Now;
    

    您正在插入一个数据类型为 Char 的日期,这看起来是错误的。

    【讨论】:

    • tnx 的答案,但仍然。我更改为日期,dbdat 其他 db___ 并且仍然显示相同的错误
    • 我注意到您也没有设置参数的长度,这可能是问题的一部分。虽然我建议您修改您的问题,以显示数据库中每个字段的数据类型。
    • 一切都是长整数,只是数据是一般日期
    • 尝试将其他的 OleDbType 更改为 BigInt 而不是 Char。
    • 我将所有内容更改为 OleDbType.integer 并将数据更改为 OleDbType.date,现在我在 try 语句中收到错误:无法将参数值从字符串转换为 Int32。我现在应该做什么?
    【解决方案2】:

    您需要转换您的数据类型:textbox.value 保存一个字符串并进行转换,您可以使用 int.Parse。

        insertCommand.Parameters.Add("@ID_zivila", OleDbType.Integer).Value = int.Parse(iDTextBox.Text);
        insertCommand.Parameters.Add("@skupaj_kalorij", OleDbType.Integer).Value = int.Parse(textBox1.Text);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-12
      相关资源
      最近更新 更多