[英]Weird behaviour when running an INSERT command (C# and XLSX)
不知何故,我無法理解我正在使用的命令的狀態。 基本上我想將數據插入EXCEL文件,如下所示:
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=scriptsdb.xlsx;Extended Properties=\"Excel 12.0;ReadOnly=False;HDR=Yes;\"";
OleDbConnection objConn = new OleDbConnection(ConnectionString);
string sSQLQuery = "INSERT INTO [Plan1$] ([ID], [NAME], [DESCRIPTION], [SQL_CODE]) VALUES ('" + NextID + "','" + txtbxName.Text + "','" + txtbxDescription.Text + "','" + txtboxSQL.Text + "')";
OleDbCommand cmd = new OleDbCommand(sSQLQuery, objConn);
objConn.Open();
cmd.ExecuteNonQuery();
現在檢查一下。 有時它可以工作(添加記錄),有時我會收到一條錯誤消息(操作必須使用可更新的查詢)。
聽起來可能很奇怪,但當“文本”字段只有一個單詞時,我只會收到錯誤消息。 例如:“ TEST”。 只要將其更改為“ TEST ONE”,它就可以正常工作。 如果我從一開始就嘗試用兩個詞保存它,那么它將起作用。
知道我做錯了什么嗎?
謝謝!!
注意:將INSERT INTO [Plan1 $]更改為INSERT INTO [Sheet1 $]。
工作代碼。
class Program
{
static void Main(string[] args)
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+"C:\\Users\\123\\Desktop\\plan1.xlsx;"+"Extended Properties=\"Excel 12.0;ReadOnly=False;HDR=Yes\";";
// here you can use your text box or from
// where ever you access the data to be inserted
// into the that Excel file sheet
string selectString = "INSERT INTO [Sheet1$] ([ID], [NAME], [DESCRIPTION], [SQL_CODE]) VALUES ('1','maziz','Not working','selectfrom you')";
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand(selectString, con);
try
{
con.Open();
cmd.ExecuteNonQuery();
Console.WriteLine("Successfully inserted the records");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
con.Close();
con.Dispose();
}
Console.ReadLine();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.