2014-12-11 2 views
0

누군가 내가 내 레코드를 MS Access에 삽입 할 수없는 이유를 설명 할 수 있습니까? 나는 인위적으로 가능한 모든 것을 시도했지만, 내가해야 할 일을시키지 않을 것이다. 내가 뭘 해야하는지 내 C 샤프 프로그램에서 작성된 기록을 허용하고 내 MS 액세스에 값을 삽입합니다 버튼을 누르면됩니다.MSAccess에 레코드 삽입하기

void Insert_Record(object s, EventArgs e) 
{ 
    string dbconnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + @"data source =BookCSharp.accdb"; 
    string dbcommand = "INSERT INTO BookKey, Title, Pages from Books;"; 
    OleDbConnection conn = new OleDbConnection(dbconnection); 
    OleDbCommand comm = new OleDbCommand(dbcommand, conn); 
    OleDbDataAdapter adapter = new OleDbDataAdapter(comm);   

    conn.Open(); 

    adapter.Fill(ds, "Books"); 

    conn.Close(); 
    DataTable dt = ds.Tables[0]; 
    //define a new record and place it into a new DataRow 
    DataRow newRow = dt. NewRow(); 
    newRow["BookKey"] = txtBookKey.Text; 
    newRow["Title"] = txtTitle.Text; 
    newRow["Pages"] = txtPages.Text; 

    //add the new DataRow to DataTable 
    dt.Rows.Add(newRow); 

    //update DB 
    adapter.Update(ds, "Books"); 

    //accept changes 
    ds.AcceptChanges(); 

    //update listBox1 
    lstDisplayBooks.Items.Clear(); 
    foreach (DataRow row in ds.Tables[0].Rows) 
    { 
     lstDisplayBooks.Items.Add(row["BookKey"] + " " + row["Title"] + " (" + row["Pages"] + ")"); 
    } 
    txtBookKey.Enabled = false; 
    txtBookKey.Text = " "; 
    txtTitle.Enabled = false; 
    txtTitle.Text = " "; 
    txtPages.Enabled = false; 
    txtPages.Text = " "; 
    btnInsert.Enabled = false; 
} 
+0

PK 열을 정의 했습니까? IIRC 액세스가 ID 열을 지원하지 않습니다. – BradleyDotNET

+2

받고있는 오류 메시지를 게시 할 수 있습니까? – paqogomez

+1

@BradleyDotNET 예, 지원됩니다. 액세스는 "일련 번호"라고합니다. –

답변

0

OleDbDataAdapter

void Insert_Record(object s, EventArgs e) 
{ 
    string dbconnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + @"data source =BookCSharp.accdb"; 
    string dbcommand = "SELECT * FROM Books;"; 
    using(OleDbConnection conn = new OleDbConnection(dbconnection)) 
    using(OleDbCommand comm = new OleDbCommand(dbcommand, conn)) 
    { 
     OleDbDataAdapter adapter = new OleDbDataAdapter(comm); 
     OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter); 
     // See comments below for these properties 
     builder.QuotePrefix = "["; 
     builder.QuoteSuffix = "]"; 
     conn.Open();    
     adapter.Fill(ds, "Books"); 

     DataTable dt = ds.Tables[0]; 
     DataRow newRow = dt. NewRow(); 
     newRow["BookKey"] = txtBookKey.Text; 
     newRow["Title"] = txtTitle.Text; 
     newRow["Pages"] = txtPages.Text; 
     dt.Rows.Add(newRow); 
     builder.GetInsertCommand(); 
     adapter.Update(ds, "Books"); 
    } 

    //update listBox1 
    lstDisplayBooks.Items.Clear(); 
    foreach (DataRow row in ds.Tables[0].Rows) 
    { 
     lstDisplayBooks.Items.Add(row["BookKey"] + " " + row["Title"] + " (" + row["Pages"] + ")"); 
    } 
    txtBookKey.Enabled = false; 
    txtBookKey.Text = " "; 
    txtTitle.Enabled = false; 
    txtTitle.Text = " "; 
    txtPages.Enabled = false; 
    txtPages.Text = " "; 
    btnInsert.Enabled = false; 
} 

링크의 예는 OleDbCommandBuilder 포함을 위해/업데이트 방법에서 사용되는 명령을 삭제 자동 INSERT/UPDATE를 생성하는 SELECT 쿼리와 OleDBCommandBuilder 필요 이런 식으로.

코드는 초기 오류를 수정해야하지만 실제로이 시나리오에서는 OleDbDataAdapter를 사용할 필요가 없습니다. DataGridView와 같은 로컬 데이터 소스를 유지 관리 할 필요가없는 유일한 목적은 OleDbCommand를 적절한 서면 INSERT 및 매개 변수가있는 쿼리와 함께 직접 사용하는 것이 훨씬 간단합니다.

void Insert_Record(object s, EventArgs e) 
{ 
    string dbconnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + @"data source =BookCSharp.accdb"; 
    string dbcommand = "INSERT INTO Books (BookKey, Title, Pages) VALUES(?,?,?);"; 
    using(OleDbConnection conn = new OleDbConnection(dbconnection)) 
    using(OleDbCommand comm = new OleDbCommand(dbcommand, conn)) 
    { 
     conn.Open();    
     comm.Parameters.AddWithValue("@p1", txtBookKey.Text); 
     comm.Parameters.AddWithValue("@p2", txtTitle.Text); 
     comm.Parameters.AddWithValue("@p3", txtPages.Text); 
     comm.ExecuteNonQuery(); 
    } 
    ..... 
+0

감사합니다. downvoter, 좀 더주의를 기울여이 질문을 수정하도록하겠습니다. 그러나 정말로이 코드가 잘못된 것 같은 이유에 대한 의견을 남기려면 아무런 문제가 없습니다. 나는 이것이 자신의 견해를 표명하는 예의의 행위라고 생각합니다. – Steve

+0

좋은 답변이지만 OleDbCommandBuilder를 Access 데이터베이스와 함께 사용하기위한 샘플 코드는 Access builder.QuotePrefix = "[";'and.'builder.QuoteSuffix = "]";'를 포함해야합니다. 열 또는 테이블 이름으로 사용될 경우 오류가 발생합니다. –

+1

예 @GordThompson 맞습니다. OleDbCommandBuilder는이 두 속성을 정의하지 않고 비워 둡니다. 따라서 자동 생성 된 명령에서 인용되지 않은 키워드를 예약하는 위험은 실제로 있습니다. 반대로 SqlCommandBuilder는 사용자가 말하는 것처럼이 두 속성을 자동으로 정의합니다. OleDb는 이러한 속성이 지원되는 다양한 데이터베이스 시스템간에 다른지 여부를 알 수 없기 때문에 이러한 의미가 있습니다. – Steve