private void ButtonOk_Click(object sender, EventArgs e)
{
if (txtWedstrijdSchemaID.Text == "")
{
//Insert
string SQL;
SQL = "Insert into Wedstrijdschema (Team1, Team2, Datum)";
SQL += " values (";
SQL += "" + txtTeam1.Text + ",";
SQL += "" + txtTeam2.Text + ",";
SQL += "" + Convert.ToDateTime(txtDatum.Text) + "";
SQL += ")";
clDatabase.ExecuteCommand(SQL);
vulLv();
}
else
{
//Update
string SQL;
SQL = "Update Wedstrijdschema SET ";
SQL += "Team1 = " + txtTeam1.Text + ",";
SQL += "Team2 = " + txtTeam2.Text + ",";
SQL += "Datum = " + Convert.ToDateTime(txtDatum.Text) + "";
SQL += " where SchemaId = " + zoek;
clDatabase.ExecuteCommand(SQL);
vulLv();
}
txtDatum.Enabled = txtTeam2.Enabled = txtTeam1.Enabled = false;
}
这是我目前拥有的内容,因为trycatch语句,当我尝试时它不会崩溃,如果我在//insert和//upload中注释掉txtDatum.Text,它可以正常工作(但显然在数据库中将输入NULL作为日期),有人能看出我哪里错了吗?
编辑:关于参数的使用,我们需要使用三层系统,所有SQL都通过一个类进行,这是唯一允许对数据库进行任何操作的类,这是命令执行的方式。
public static bool ExecuteCommand(string SQLInstructie)
{
bool retour = true;
SqlConnection Conn = new SqlConnection(clStam.Connstr);
SqlCommand Cmd = new SqlCommand(SQLInstructie, Conn);
try
{
Cmd.Connection.Open();
Cmd.ExecuteNonQuery();
}
catch
{
retour = false;
}
finally
{
Conn.Close();
}
return retour;
}
这个可以用了!!非常感谢您的帮助:
private void ButtonOk_Click(object sender, EventArgs e)
{
if (txtWedstrijdSchemaID.Text == "")
{
//Insert
string SQL;
SQL = "Insert into Wedstrijdschema (Team1, Team2, Datum)";
SQL += " values (";
SQL += "" + txtTeam1.Text + ",";
SQL += "" + txtTeam2.Text + ",";
SQL += "'" + Convert.ToDateTime(txtDatum.Text) + "'";
SQL += ")";
Debug.WriteLine(SQL);
clDatabase.ExecuteCommand(SQL);
vulLv();
}
else
{
//Update
string SQL;
SQL = "Update Wedstrijdschema SET ";
SQL += "Team1 = " + txtTeam1.Text + ",";
SQL += "Team2 = " + txtTeam2.Text + ",";
SQL += "Datum = '" + Convert.ToDateTime(txtDatum.Text) + "'";
SQL += " where SchemaId = " + zoek;
clDatabase.ExecuteCommand(SQL);
vulLv();
}
txtDatum.Enabled = txtTeam2.Enabled = txtTeam1.Enabled = false;
}
编辑:我承诺从现在开始使用参数化SQL!
'
并运行代码,看看会发生什么。 - Alex K.Convert.ToDateTime(txtDatum.Text)
可能不会给出正确的格式;它将变成19-6-2015 14:49:23
或类似的格式(ToString()被隐式调用)。而且,由于您正在使用荷兰系统,这取决于文化设置(别担心;我也是荷兰人)。您需要知道您的数据库对字符串期望什么样的格式,并进行相应的格式调整。 - SjipsclDatabase.ExecuteCommand(SQL);
之前,请添加一行Debug.WriteLine(SQL);
。检查输出窗口。SQL 是什么样子的? - Sjips