我在WPF中的应用程序允许用户将文本框中的某些数据保存到Excel文件中(使用OLEDB连接)。我希望添加功能,每次将新行保存到Excel文件中时,都会在该Excel文件的EventID列中添加序列号。
但是运行与参数@EventId相关的应用程序时出现错误,提示:“参数没有默认值”。 我希望我写错了sql1命令来生成序列号。
感谢您的帮助。
private void btnSaveNewEvent1_Click_1(object sender, RoutedEventArgs e)
{
object eventName = txtEventName.Text;
object typeValue = txtEventType.Text;
object nameValue = txtAttributeName.Text;
object attribvValue = txtAValue.Text;
object descValue = txtEventDescrip.Text;
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
System.Data.OleDb.OleDbCommand myCommand1 = new System.Data.OleDb.OleDbCommand();
String sql = null;
String sql1 = null;
MyConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source='excel_file\\events2.xlsx'; " +
"Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"");
try
{
//SQL STATEMENT TO SAVE INSERTED BY THE USER VALUES FROM THE TEXT BOXES
//SQL1 STATEMENT TO GENERATE EVENTID NUMBER EACH TIME THE USER SAVES NEW ROW OF DATA
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Insert into [events$] (EventID,EventName, Type, Name, [Value], Description) values(@EventID,@EventName,@Type,@Name,@Val,@Desc)";
myCommand.CommandText = sql;
myCommand.Parameters.AddWithValue("@EventID",sql1);
myCommand.Parameters.AddWithValue("@EventName", eventName ?? DBNull.Value);
myCommand.Parameters.AddWithValue("@Type", typeValue ?? DBNull.Value);
myCommand.Parameters.AddWithValue("@Name", nameValue ?? DBNull.Value);
myCommand.Parameters.AddWithValue("@Val", attribvValue ?? DBNull.Value);
myCommand.Parameters.AddWithValue("@Desc", descValue ?? DBNull.Value);
myCommand1.Connection = MyConnection;
sql1= "DECLARE @i int = 0 while @i < EventID BEGIN SET @i = EventID + 1 END";
myCommand1.CommandText = sql1;
myCommand.ExecuteNonQuery();
myCommand1.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
MyConnection.Close();
Events eventsWindow = new Events();
eventsWindow.dgData.Items.Refresh();
}
}
答案 0 :(得分:0)
由于您的命令在command1 sql1 = null之前运行,这就是您的问题所在。 您需要在执行命令之前设置sql1的值。如果您确实希望该值为null,则需要使用DBNull.Value,就像其他参数一样。