1

该程序使用 C# WinForms 和 SQL Server 2008。当我想输入包含来自 DateTimePicker 的值的数据时,我可以看到措辞是荷兰语,然后我收到关于转换值的错误。有没有办法预先编程来解决这个问题?我发现了错误,就在这里。

错误

        try
        {
            SqlConnection connect = new SqlConnection("Data Source=Localhost\\SQLExpress;Initial Catalog=DataBase;Integrated Security=True");
            SqlDataAdapter da = new SqlDataAdapter();

            /******************** Inserting ********************/
            string query = "INSERT INTO spending VALUES (";
            query += "'" + date_dateTimePicker.Value + "', "; // Date
            query += "'" + Convert.ToDecimal(amount_spent_textBox.Text) + "', "; // Amount spent
            query += "'" + spent_on_textBox.Text + "')"; // Spent on
            connect.Open();
            da.InsertCommand = new SqlCommand(query, connect);
            da.InsertCommand.ExecuteNonQuery();

            connect.Close();
        }

        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
        }

事情变得越来越复杂。我在尝试将 dateTimePicker 值插入数据库时​​遇到了这个错误,就像我对上面的代码所做的那样。它在我的电脑上运行得很好,但在这里不行。有人可以解释吗?这是错误:

错误

使用的代码:

string update = "UPDATE table SET the_date = '" + the_date_dateTimePicker.Value + "' WHERE instance_ID = 1";
        connect.Open();
        da.InsertCommand = new SqlCommand(update, connect);
        da.InsertCommand.ExecuteNonQuery();
        connect.Close();

好的,这是我现在正在处理的表单的完整代码,即显示此错误的代码。大多数表格的结构都是这样的,所以如果我把这个做对了,其余的应该不会有任何问题。我正在我的电脑上测试它,所以如果它在这里工作,它也应该在那里工作。

看看,我不知道该怎么办了。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace TheNamespace
{
public partial class submit_spending : Form
{
    public submit_spending()
    {
        InitializeComponent();
    }

    private void submit_button_Click(object sender, EventArgs e)
    {
        try
        {
            SqlConnection connect = new SqlConnection("Data Source=Localhost\\SQLExpress;Initial Catalog=TheDataBase;Integrated Security=True");
            SqlDataAdapter da = new SqlDataAdapter();

            /******************** Inserting ********************/
            string query = "INSERT INTO spending VALUES (@date, @amount_spent, @spent_on)";
            SqlCommand command = new SqlCommand(query);
            command.Parameters.AddWithValue("date", date_dateTimePicker.Value);
            command.Parameters.AddWithValue("amount_spent", Convert.ToDecimal(amount_spent_textBox.Text));
            command.Parameters.AddWithValue("spent_on", spent_on_textBox.Text);

            connect.Open();
            da.InsertCommand = new SqlCommand(query, connect);
            da.InsertCommand.ExecuteNonQuery();
            connect.Close();

            if (MessageBox.Show("Submitted.", "Spending submitted", MessageBoxButtons.OK) == DialogResult.OK)
            {
                this.Close();
            }
        }
        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
        }
    }

    private void cancel_button_Click(object sender, EventArgs e)
    {
        this.Close();
    }
}
}
4

7 回答 7

7

您应该使用该Parameters.AddWithValue()方法。我希望它能够DateTime正确格式化。

string cmdText = "UPDATE table SET colX = @value WHERE id = @currId";
var cmd = new SqlCommand(cmdText, conn);
cmd.Parameters.AddWithValue("value", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("currId", id);
于 2012-05-21T08:56:15.167 回答
3

可能您的日期时间格式有问题,可以通过将系统日期时间格式更改为与它正在工作的计算机相同的格式来解决,或者您可以在代码中做一些额外的工作。对于自定义日期时间格式看看这里:http: //msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

于 2012-05-21T00:31:46.903 回答
1

理想情况下,您应该使用 T-SQL 语句中的参数编写应用程序datetime,这样转换就不会出现。

您可以使用的另一种方法是SET DATEFORMAT在您的应用程序使用的连接上添加一个。因此,您可以将格式更改为您的应用程序期望/使用的格式。

于 2012-05-28T08:38:46.657 回答
1

我认为您需要在 command.Parameters 中将值分配给日期时指定 SqlDBType 。请交叉检查您在 insert 语句中指定的参数名称与参数中指定的参数。添加

string sql = "INSERT INTO spending VALUES (@date, @amount_spent, @spent_on)";
 using (var cn = new SqlConnection("..connection string.."))
 using (var cmd = new SqlCommand(sql, cn))
   {
cmd.Parameters.Add("@date", SqlDbType.DateTime).Value = date_dateTimePicker.Value;
command.Parameters.AddWithValue("@amount_spent",Convert.ToDecimal(amount_spent_textBox.Text));
        command.Parameters.AddWithValue("@spent_on", spent_on_textBox.Text);

        connect.Open();

有时最好使用不变的文化来存储数据库中的日期/时间之类的东西。你可以试试 CultureInfo.Invariantculture

DateTime date = date_dateTimePicker.Value.Date;
string sDate = date.ToString("dd-MM-yy",    System.Globalization.CultureInfo.InvariantCulture);
DateTime dateInsert = Convert.ToDateTime(sDate); 
于 2012-05-30T02:12:29.760 回答
1

您可能可以使用具有文化不变格式的显式 ToString 来确保它适用于任何语言环境。这有点骇人听闻,但替换了这一行:

command.Parameters.AddWithValue("date", date_dateTimePicker.Value);

这应该可以工作:

command.Parameters.AddWithValue("date", date_dateTimePicker.Value.ToString("s"));

这将为您提供 ISO 8601 格式的日期时间字符串,这是一个具有明确规范的国际标准。此外,此格式不受 SQL Server 实例上的 SET DATEFORMAT 或 SET LANGUAGE 设置的影响。

于 2012-05-31T16:12:31.120 回答
0

只需使用dateTime.ToString("s"),无论计算机的文化设置如何,它都会以通用格式提供您的日期时间。

于 2012-05-21T07:17:44.723 回答
0
"UPDATE table SET the_date = '" + the_date_dateTimePicker.Value + "' WHERE instance_ID = 1";

此处使用默认 CultureInfo 转换为字符串。根据工作站上选择的区域设置,日期时间可以转换为“29/05/2012”和“05/29/2012”。但是 Sql Server 可能配置为其他区域设置,因此您遇到问题(sql server 无法解析传递的 DateTime 字符串表示形式)

如果您不想稍后再遇到与 CultureInfo 相关的问题,则必须使用参数化查询。

于 2012-05-29T14:53:21.547 回答