2014-01-22 109 views
-3

我已經編寫了一個代碼來完成上述任務。沒有錯誤,但訪問數據庫沒有得到更新。使用c#表單應用程序更新Access數據庫

private void button1_Click(object sender, EventArgs e) 
    { 
     OleDbConnection mycon = new OleDbConnection(); 
     mycon.ConnectionString [email protected]"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Dinesh\C#\GIS_Power\WindowsFormsApplication1\bin\Power_DB1"; 
     OleDbCommand command = new OleDbCommand(); 
     command.CommandText = "INSERT INTO Table1 (Emp_ID,Asset_ID)VALUES('" + textBox1.Text + "','" + textBox2.Text + "')"; 
    } 

回答

0

你沒有執行命令。請執行插入語句,然後僅插入數據到數據庫中

這將解決您的問題。

OleDbCommand command = new OleDbCommand("//Isert statment here", mycon); 
command.ExecuteNonQuery(); 
+0

謝謝。問題解決了。感謝所有.. – user3219362

+0

在這種情況下,率將非常感激:) – Nil23

2

問題1:需要使用ExecuteNonQuery()方法來執行命令。

問題2:您沒有通過Connection對象調用Open()方法打開與數據庫的連接。

問題3:您沒有將Connection對象指定給Command對象。

建議:INERT INTO聲明是開放的SQL Injection Attacks,所以我建議你使用Parameterised queries避免。

完整代碼:

OleDbConnection mycon = new OleDbConnection(); 
mycon.ConnectionString [email protected]"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Dinesh\C#\GIS_Power\WindowsFormsApplication1\bin\Power_DB1"; 
OleDbCommand command = new OleDbCommand(); 

command.CommandText = "INSERT INTO Table1 (Emp_ID,Asset_ID) VALUES(@empID,@assetID)"; 
command.Parameters.AddWithValue("@empID",textBox1.Text); 
command.Parameters.AddWithValue("@assetID",textBox2.Text); 
mycon.Open(); 
command.Connection=mycon; 
command.ExecuteNonQuery(); 
+0

建議:使用'using'連接和(可能?)命令。 – Sinatr

0

您創建了連接字符串但未打開連接。

您創建了查詢但未執行該查詢。

解決方案:

您需要openconnectionexecute查詢也是如此。

代碼:

OleDbConnection mycon = new OleDbConnection(); 
mycon.ConnectionString [email protected]"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Dinesh\C#\GIS_Power\WindowsFormsApplication1\bin\Power_DB1"; 
mycon.Open(); //opening connection 

OleDbCommand command = new OleDbCommand(); 
command.CommandText = "INSERT INTO Table1 (Emp_ID,Asset_ID)VALUES('" + textBox1.Text + "','" + textBox2.Text + "')"; 
command.ExecuteNonQuery(); //executing query 

mycon.Close(); //close the connection after executing the query 
0

使用

mycon.open() 
command.CommandText = "INSERT INTO Table1 (Emp_ID,Asset_ID)VALUES('" + textBox1.Text + "','" + textBox2.Text + "')"; 
command.ExecuteNonQuery(); 
相關問題