m0_46820994
2020-09-01 23:00
采纳率: 57.1%
浏览 166

“System.Data.OleDb.OleDbException”类型的未经处理的异常在 System.Data.dll 中发生 其他信息: 操作必须使用一个可更新的查询。

DateTime localTime = DateTime::Now; //当前时间
DateTime startTime = DateTime::Now; //开始按钮时间
DateTime endTime = DateTime::Now; //结束按钮时间
array^ DataFromSensor = gcnew array(50);
array^ Sensor1T = gcnew array(20); //存储传感器1的温度数据
array^ Sensor1H = gcnew array(20); //存储传感器1的湿度数据
array^ Sensor2T = gcnew array(20); //存储传感器2的温度数据
array^ Sensor2H = gcnew array(20); //存储传感器2的湿度数据
array^ Sensor3T = gcnew array(20); //存储传感器3的温度数据
array^ Sensor3H = gcnew array(20); //存储传感器3的湿度数据
array^ Sensor4T = gcnew array(20); //存储传感器4的温度数据
array^ Sensor4H = gcnew array(20); //存储传感器4的湿度数据
unsigned char RecvFlag = 0; //数据接收正确标志
unsigned char RecvErrorFromSensor = 0; //STM32与PC通讯错误标志
unsigned char ArrayNumSensor = 0; //传感器数据数组索引
array^ OrderToSensor = gcnew array(1);
float time_1ms = 0; //timer2定时标志位
bool time_flag = false; //timer1定时标志位
bool ArrayIsFull = false;
String^ str;
System::Data::DataTable^ myTable = gcnew System::Data::DataTable();
System::Data::DataSet^ myDataSet = gcnew System::Data::DataSet();

private: System::Void port_DataReceived(System::Object^ sender, System::IO::Ports::SerialDataReceivedEventArgs^ e)
{
//serialPort1->DataReceived += gcnew System::IO::Ports::SerialDataReceivedEventHandler(this, &MyForm::port_DataReceived);
try
{
int ilen = serialPort1->BytesToRead;
cli::array^ bytes = gcnew array(ilen);
serialPort1->Read(DataFromSensor, 0, ilen);
if (DataFromSensor[0] == 0x64)
{
RecvFlag = 1;
}
else
{
RecvErrorFromSensor = 1;
}
if (RecvFlag == 1)
{

if (time_flag == true)
{
DisplayDataInText();
DataToArray();
String^ str = System::Text::Encoding::Default->GetString(DataFromSensor);
tbxRecv->AppendText(str);

        }
        else
        {
            //tbxRecv->AppendText(DataFromSensor[1].ToString());
            tbxRecv->AppendText("time_flar==false");
        }
    }
}
catch(...)
{
    toolStripStatusLabel1->Text = "串口数据接收出错,请检查!\r\n";
}

}

public:System::Void DisplayDataInText()
{
String^ str = System::Text::Encoding::Default->GetString(DataFromSensor);
String^ str1 = str->Remove(0, 1);
String^ str2 = str1->Remove(4);
tbxTemp1->Text = str2; //显示传感器1的温度
String^ str3 = str1->Remove(0, 4);
String^ str4 = str3->Remove(4);
tbxHumi1->Text = str4; //显示传感器1的湿度

String^ str5 = str1->Remove(0, 8);
String^ str6 = str5->Remove(4);
tbxTemp2->Text = str6;              //显示传感器2的温度
String^ str7 = str1->Remove(0, 12);
String^ str8 = str7->Remove(4);
tbxHumi2->Text = str8;              //显示传感器2的湿度

String^ str9 = str1->Remove(0, 16);
String^ str10 = str9->Remove(4);
tbxTemp3->Text = str10;             //显示传感器3的温度
String^ str11 = str1->Remove(0, 20);
String^ str12 = str11->Remove(4);
tbxHumi3->Text = str12;             //显示传感器3的湿度

String^ str13 = str1->Remove(0, 24);
String^ str14 = str13->Remove(4);
tbxTemp4->Text = str14;             //显示传感器4的温度
String^ str15 = str1->Remove(0, 28);
String^ str16 = str15->Remove(4);
tbxHumi4->Text = str16;             //显示传感器4的湿度

}

public:System::Void DataToArray()
{
while (tbxTemp1->Text != ""|| tbxTemp2->Text != ""|| tbxTemp3->Text != ""|| tbxTemp4->Text != "")
{
for (ArrayNumSensor = 0; ArrayNumSensor < 20; ArrayNumSensor++)
{
Sensor1T[ArrayNumSensor] = Convert::ToSingle(tbxTemp1->Text);
Sensor1H[ArrayNumSensor] = Convert::ToSingle(tbxHumi1->Text);
Sensor2T[ArrayNumSensor] = Convert::ToSingle(tbxTemp2->Text);
Sensor2H[ArrayNumSensor] = Convert::ToSingle(tbxHumi2->Text);
Sensor3T[ArrayNumSensor] = Convert::ToSingle(tbxTemp3->Text);
Sensor3H[ArrayNumSensor] = Convert::ToSingle(tbxHumi3->Text);
Sensor4T[ArrayNumSensor] = Convert::ToSingle(tbxTemp4->Text);
Sensor4H[ArrayNumSensor] = Convert::ToSingle(tbxHumi4->Text);
}
if (ArrayNumSensor = 19)
{
ArrayIsFull = true;
ArrayNumSensor = 0;
}
}
}
public:System::Void ClearText() //清除文本框的内容
{
tbxTemp1->Clear();
tbxHumi1->Clear();
tbxTemp2->Clear();
tbxHumi2->Clear();
tbxTemp3->Clear();
tbxHumi3->Clear();
tbxTemp4->Clear();
tbxHumi4->Clear();
}
private: System::Void btnLink_Click(System::Object^ sender, System::EventArgs^ e) //连接
{
toolStripStatusLabel2->Text = "开始自动配置串口";
toolStripStatusLabel2->Text = "串口扫描";
toolStripStatusLabel2->Text = "端口扫描完毕";
toolStripStatusLabel2->Text = "正在配置波特率";
comboBox1->Items->Clear();
bool comExistence = false;
for (int i = 0; i < 15; i++)
{
try
{
SerialPort^ serialPort = gcnew SerialPort("COM" + (i + 1).ToString());
serialPort->Open();
serialPort->Close();
comboBox1->Items->Add("COM" + (i + 1).ToString());
comExistence = true;
}
catch (...)
{
continue;
}
}
if (comExistence)
{
comboBox1->SelectedIndex = 0;
}
else
{
MessageBox::Show("没有找到可用的串口!");
}
serialPort1->BaudRate = Convert::ToInt32(comboBox2->Text);
toolStripStatusLabel2->Text = "自动配置完成";
if (btnLink->Text == "连接")
{
try
{
serialPort1->PortName = comboBox1->Text;
serialPort1->BaudRate = Convert::ToInt32(comboBox2->Text);
serialPort1->Open();
btnLink->Text = "断开";
comboBox1->Enabled = false;
comboBox2->Enabled = false;
toolStripStatusLabel2->Text = "串口已连接\r\n";

}
catch (...)
{
if (serialPort1->IsOpen)
serialPort1->Close();
btnLink->Text = "连接";
comboBox1->Enabled = true;
comboBox2->Enabled = true;

toolStripStatusLabel2->Text = "请检查串口连接\r\n";
}
}
else if (btnLink->Text == "断开")
{
try
{
serialPort1->Close();
btnLink->Text = "连接";
comboBox1->Enabled = true;
comboBox2->Enabled = true;

toolStripStatusLabel2->Text = "串口已断开\r\n";
}
catch (...) {}
}
}

public: System::Void OpenAccess() //连接数据库,在表格显示
{
String^ oleDBString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Office2019\MyProject\sensor.accdb;";
OleDbConnection^ os = gcnew OleDbConnection(oleDBString);
String^ sql = "select* from Sensor";
DataSet^ ds = gcnew DataSet();
OleDbDataAdapter^ oleDbDataAdapter = gcnew OleDbDataAdapter(sql, os);
oleDbDataAdapter->Fill(ds,"Sensor");
//dataGridView1->DataSource = ds->Tables[0]->DefaultView;
os->Close();
}

private: System::Void MyForm_Load(System::Object^ sender, System::EventArgs^ e)
{
String^ text1 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Office2019\MyProject\sensor.accdb;";
OleDbConnection^ conn = gcnew OleDbConnection(text1);
String^ txtCommand = "select Num,Time,Temperature1,Humidity1,Temperature2,Humidity2,Temperature3,Humidity3,Temperature4,Humidity4,TemperatureSet,HumiditySet from Sensor";
OleDbDataAdapter^ adapter = gcnew OleDbDataAdapter(txtCommand, conn);
//DataSet^ myDs = gcnew DataSet();
adapter->Fill(myDataSet, "Sensor");
myTable = myDataSet->Tables[0];
dataGridView1->DataSource = myDataSet;
dataGridView1->DataMember = "Sensor";

toolStripStatusLabel2->Text = "";

}

/***************导出Excel报表***********************/
public: static bool outExcel(System::Data::DataTable^ dt, String^ strFilePath, String^ tableheader, String^ columname)
{
try
{
String^ strBufferLine = "";
StreamWriter^ strWriterObj = gcnew StreamWriter(strFilePath, false, System::Text::Encoding::UTF8);
strWriterObj->WriteLine(tableheader);
strWriterObj->WriteLine(columname);
for (int i = 0; i < dt->Rows->Count; i++)
{

strBufferLine = "";
for (int j = 0; j < dt->Columns->Count; j++)
{
if (j > 0)
strBufferLine += ",";
strBufferLine += dt->Rows[i][j]->ToString();
}
strWriterObj->WriteLine(strBufferLine);
}
strWriterObj->Close();
return true;
}
catch (...)
{
return false;
}
}

/*****************List转DataTable********************************/

//public: static System::Data::DataTable ToDataTable(IEnumerable collection)

/*****************创建Excel报表********************************/
private:System::Void CreateExcel()
{
Microsoft::Office::Interop::Excel::Application^ exApp = gcnew Microsoft::Office::Interop::Excel::ApplicationClass();
Microsoft::Office::Interop::Excel::Workbook^ exWb = exApp->Workbooks->Add(Type::Missing);
try
{

exApp->Visible = false;
exApp->DisplayAlerts = false;
exApp->AlertBeforeOverwriting = true;
exWb->SaveAs("E:\Office2019\MyProject",Missing::Value,Missing::Value, Missing::Value, Missing::Value, Missing::Value,
Microsoft::Office::Interop::Excel::XlSaveAsAccessMode::xlNoChange, Missing::Value, Missing::Value, Missing::Value,
Missing::Value, Missing::Value);
exWb = nullptr;
exApp->Quit();
exApp = nullptr;
}
catch (Exception^ err)
{
MessageBox::Show("Excel操作出错!错误原因:"+err->Message,"提示信息",
MessageBoxButtons::OK,MessageBoxIcon::Information);
}
}

/*****************读取Excel报表********************************/
public:static System::Data::DataTable^ ReadExcel(String^ filePath)
{
try
{
String^ strConn;
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=yes;IMEX=2'";
OleDbConnection^ OleConn = gcnew OleDbConnection;
OleConn->Open();
String^ sql = "select* from [sheet1$]";
OleDbDataAdapter^ OleDaExcel = gcnew OleDbDataAdapter(sql, OleConn);
DataSet^ OleDsExcel = gcnew DataSet();
OleDaExcel->Fill(OleDsExcel, "sheet1$");
OleConn->Close();

    return OleDsExcel->Tables["sheet1$"];
}
    catch (Exception^ err)
    {
        MessageBox::Show("数据绑定Excel失败!失败原因:" + err->Message, "提示信息",
            MessageBoxButtons::OK, MessageBoxIcon::Information);
        return nullptr;
    }   

}

/*****************修改Excel报表********************************/
private:System::Void DoSql(String^ strsql, String^ filePath)
{
try
{
String^ ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=yes;IMEX=2'";
OleDbConnection^ OledCon = gcnew OleDbConnection(ConnectionString);
OledCon->Open();
OleDbCommand^ OledCom = gcnew OleDbCommand(strsql, OledCon);
OledCom->ExecuteNonQuery();
OledCon->Close();
}
catch (Exception^ err)
{
MessageBox::Show("Excel修改失败!失败原因:" + err->Message, "提示信息",
MessageBoxButtons::OK, MessageBoxIcon::Information);
}
}

/*****************生成Excel报表********************************/
private: System::Void btnExcel_Click(System::Object^ sender, System::EventArgs^ e)
{
//创建报表
Microsoft::Office::Interop::Excel::Application^ exApp = gcnew Microsoft::Office::Interop::Excel::ApplicationClass();
Microsoft::Office::Interop::Excel::Workbook^ exWb = exApp->Workbooks->Add(Type::Missing);
Microsoft::Office::Interop::Excel::Worksheet^ exWs;
try
{
exApp->Visible = false;
exApp->DisplayAlerts = false;
exApp->AlertBeforeOverwriting = true;
exWb->SaveAs("E:\Office2019\MyProject", Missing::Value, Missing::Value, Missing::Value, Missing::Value, Missing::Value,
Microsoft::Office::Interop::Excel::XlSaveAsAccessMode::xlNoChange, Missing::Value, Missing::Value, Missing::Value,
Missing::Value, Missing::Value);
exWb = nullptr;
exApp->Quit();
exApp = nullptr;
}
catch (Exception^ err)
{
MessageBox::Show("Excel操作出错!错误原因:" + err->Message, "提示信息",
MessageBoxButtons::OK, MessageBoxIcon::Information);
}

//存入数据
for (int i = 0; i < myTable->Columns->Count; i++)
{
    exWs->Cells[1, i + 1] = myTable->Columns[i]->ColumnName;
}
for (int j = 0; j < myTable->Rows->Count; j++)
{
    for (int k = 0; k < myTable->Columns->Count; k++)
    {
        exWs->Cells[j + 2, k + 1] = myTable->Rows[j][k];
    }
}
/**********************************************
String^ filepath = "E:\\Office2019\\MyProject";
String^ commandText = "SELECT* INTO[EXCEL 8.0; DATABASE = E:\Office2019\MyProject.xlsx].sheet3 FROM Sensor;";
String^ commandText2 = "INSERT INTO [sheet1$](Temperature1,Humidity1) VALUES(22.3,68.3)";
DoSql(commandText2, filepath);

//Access数据导出Excel
OleDbConnection^ conn = gcnew OleDbConnection();
try
{
    SaveFileDialog^ saveFile = gcnew SaveFileDialog();
    saveFile->Filter = ("Excel文件(*.xls)|*.xls");
    if (saveFile->ShowDialog() == System::Windows::Forms::Form::DialogResult);//ok
    {
        String^ filename = saveFile->FileName;
        if (System::IO::File::Exists(filename))
        {
            System::IO::File::Delete(filename);
        }
        int index = filename->LastIndexOf("//");
        filename = filename->Substring(index + 1);
        String^ sql = "select top 65535* into [Excel 8.0;database=" + filename + "].[用户信息] from Users2";
        conn->ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + System::Windows::Forms::Application::StartupPath + "//Appdata,mdb";
        OleDbCommand^ com = gcnew OleDbCommand(sql, conn);
        conn->Open();
        com->ExecuteNonQuery();
        MessageBox::Show("导出数据成功", "导出数据", MessageBoxButtons::OK, MessageBoxIcon::Information); 
    }
}
catch (Exception^ err)
{
    MessageBox::Show(err->ToString());
}
finally
{
    conn->Close();
}
***************************************/

exApp->Visible = true;  //可视

}
//字段的数据类型,和传入的类型不匹配。修改下查询。字符串要引号,非字符串不要引号。
private: System::Void timer3_Tick(System::Object^ sender, System::EventArgs^ e)
{
while (tbxHumi1->Text != "" || tbxTemp1->Text != "")
{
String^ text1 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Office2019\MyProject\sensor.accdb;";
String^ text2 = "INSERT INTO Sensor(Temperature1,Humidity1,Temperature2,Humidity2,Temperature3,Humidity3,Temperature4,Humidity4)Values('";
text2 += tbxTemp1+ "','";
text2 += tbxHumi1+ "','";
text2 += tbxTemp2 + "','";
text2 += tbxHumi2 + "','";
text2 += tbxTemp3 + "','";
text2 += tbxHumi3 + "','";
text2 += tbxTemp4 + "','";
text2 += tbxHumi4 + "')";
OleDbConnection^ conn = gcnew OleDbConnection(text1);
conn->Open();
OleDbCommand^ da = gcnew OleDbCommand();
da->CommandText = text2;
da->Connection = conn;
da->ExecuteNonQuery();

conn->Close();
ClearText();
}
}

/*********更新记录入数据库***************/
private: System::Void btnGenerate_Click(System::Object^ sender, System::EventArgs^ e) {
String^ text3 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Office2019\MyProject\sensor.accdb;";
OleDbConnection^ conn = gcnew OleDbConnection(text3);
String^ text4 = "select Num,Time,Temperature1,Humidity1,Temperature2,Humidity2,Temperature3,Humidity3,Temperature4,Humidity4,TemperatureSet,HumiditySet from Sensor2";
OleDbDataAdapter^ command = gcnew OleDbDataAdapter(text4, conn);
DataSet^ ds = gcnew DataSet("ds");
command->Fill(ds, "Sensor2");
dataGridView1->DataSource = ds;
dataGridView1->DataMember = "Sensor2";
}

//---添加接受消息到列表的委托的方法
private: System::Void AddMessageToList(String^ text)
{
tbxRecv->AppendText(text);
}

private: System::Void sortProcess_OutputDataReceive(System::Object^ sender, System::Diagnostics::DataReceivedEventArgs^ e)
{
tbxRecv->AppendText("\r\n");
if (!String::IsNullOrEmpty(e->Data))
{
tbxRecv->AppendText("\r\n" + e->Data + "\r\n");
//this->BeginInvoke(gcnew Action(() => {textBox1->AppendText("\r\n" + e->Data + "\r\n"); })); //修改
}
tbxRecv->AppendText("\r\n");
}

private: System::Void ExcuteDosCommand(String^ cmd)//add
{
try
{
System::Diagnostics::Process^ p = gcnew System::Diagnostics::Process;
p->StartInfo->FileName = "cmd";
p->StartInfo->UseShellExecute = false;
p->StartInfo->RedirectStandardInput = true;
p->StartInfo->RedirectStandardOutput = true;
p->StartInfo->RedirectStandardError = true;
p->StartInfo->CreateNoWindow = true;
p->OutputDataReceived += gcnew System::Diagnostics::DataReceivedEventHandler(this, &MyForm::sortProcess_OutputDataReceive);
p->Start();
System::IO::StreamWriter^ cmdWriter = p->StandardInput;
p->BeginErrorReadLine();
if (!String::IsNullOrEmpty(cmd))
{
cmdWriter->WriteLine(cmd);
}
cmdWriter->Close();
p->WaitForExit();
p->Close();
}
catch (...)
{
MessageBox::Show("执行命令失败,请检查输入的命令是否正确!");
}
}

private: System::Void btnStart_Click(System::Object^ sender, System::EventArgs^ e) //开始
{
if (btnStart->Text == "开始")
{
startTime = DateTime::Now;
btnStart->Text = "结束";
timer1->Start(); //绘图
time_flag = true;
timer2->Start(); //PC向传感器取值
}
else
{
endTime = DateTime::Now;
btnStart->Text = "开始";
timer1->Stop();
time_flag = false;
timer2->Stop();
time_1ms = 0;
}
}

int time_out = 0;
array^ myTempArray = gcnew array(20);
Random^ random = gcnew Random();
int temp;
int arrayNum = 0;

private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e)
{
toolStripStatusLabel1->Text = DateTime::Now.ToString();
if (time_out == 0)
{
time_out = 2; //time_out = Convert::ToInt16(comboBox5->Text);
try
{
System::Text::Encoding^ gb = System::Text::Encoding::GetEncoding("gb2312");
}

catch (...)
{

toolStripStatusLabel2->Text = "串口数据写入错误\r\n";
serialPort1->Close();
btnLink_Click(sender, e);
}
}
/***********
if (time_out == 1)
{
array^ y = gcnew array(20);
for (int pointIndex = 0; pointIndex < 10; pointIndex++)
{
for (int i = 0; i < 20; i++)
{
y[i] = random->Next(45, 95);
}
//chart1->Series["Series1"]->Points->AddY(random->Next(45, 95));
chart1->Series[0]->Points->DataBindY(y);
}
}
*************/
if (time_out == 1)
{
time_out--;

for (int i = 0; i < 19; i++)
{
myTempArray[i] = random->Next(45, 50);
//myTempArray[i] = myTempArray[i + 1];

}
chart1->ChartAreas[0]->AxisY->Maximum = 100;
chart1->ChartAreas[0]->AxisY->Minimum = -10;

    if (ckb_Sensor1T->Checked)
        chart1->Series[0]->Points->DataBindY(myTempArray);
        //chart1->Series[0]->Points->DataBindY(Sensor1T);
    else if (ckb_Sensor1H->Checked)
        chart1->Series[0]->Points->DataBindY(Sensor1H);
    else if (ckb_Sensor2T->Checked)
        chart1->Series[0]->Points->DataBindY(Sensor2T);
    else if (ckb_Sensor2H->Checked)
        chart1->Series[0]->Points->DataBindY(Sensor2H);
    else if (ckb_Sensor3T->Checked)
        chart1->Series[0]->Points->DataBindY(Sensor3T);
    else if (ckb_Sensor3H->Checked)
        chart1->Series[0]->Points->DataBindY(Sensor3H);
    else if (ckb_Sensor4T->Checked)
        chart1->Series[0]->Points->DataBindY(Sensor4T);
    else
        chart1->Series[0]->Points->DataBindY(Sensor4H);
}

else time_out--;

}

private: System::Void timer2_Tick(System::Object^ sender, System::EventArgs^ e)
{
if (time_1ms == (Convert::ToSingle(comboBox6->Text)*10))
{
tbxTips->Clear();
OrderToSensor[0] = 0x44;
if (serialPort1->IsOpen)
{
serialPort1->Write(OrderToSensor, 0, 1);
}

tbxTips->Text = "向传感器取值!!!";
time_1ms = 0;
}
else
{
time_1ms++;
}
}

private: System::Void MyForm_FormClosing(System::Object^ sender, System::Windows::Forms::FormClosingEventArgs^ e)
{
/****************
DialogResult result;
result = MessageBox::Show("确定退出吗?", "退出", MessageBoxButtons->OKCancel, MessageBoxIcon->Question);
if (result == DialogResult.OK)
{
Application.ExitThread();
}
else
{
e->Cancel = true;
}
************************/
System::Diagnostics::Process^ currentProcess = gcnew System::Diagnostics::Process;
currentProcess->Kill();
}
public:static String^ GetTimeStamp()
{
System::DateTime^ localDate = System::DateTime::Now;
return localDate->ToString();

}

};
}

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • 蒋晟 2020-09-02 01:51

    手动打开一下Access数据库,修改一下数据再保存,看看是不是有文件权限或者其他应用程序锁定的问题

    打赏 评论
  • threenewbee 2020-09-02 06:58

    看看是不是access文件被锁定,或者程序没有写入的权限。

    打赏 评论

相关推荐 更多相似问题