该程序使用 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();
}
}
}