문제

테이블에 행을 삽입하는 쿼리가 있으며,이 필드는 ID라는 필드가 있으며 열에 auto_increment를 사용하여 채워집니다. 다음 기능에 대해이 값을 얻어야하지만 다음을 실행하면 실제 값이 0이 아니더라도 항상 0을 반환합니다.

MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertInvoice;
comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', " + bookFee + ", " + adminFee + ", " + totalFee + ", " + customerID +  ")";
int id = Convert.ToInt32(comm.ExecuteScalar());

내 이해에 따르면, 이것은 ID 열을 반환해야하지만 매번 0을 반환합니다. 어떤 아이디어?

편집하다:

내가 달릴 때 :

"INSERT INTO INVOICE (INVOICE_DATE, BOOK_FEE, ADMIN_FEE, TOTAL_FEE, CUSTOMER_ID) VALUES ('2009:01:01 10:21:12', 50, 7, 57, 2134);last_insert_id();"

나는 얻다:

{"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'last_insert_id()' at line 1"}
도움이 되었습니까?

해결책

편집 : Last_insert_id ()에 대한 참조 전에 "선택"이 추가되었습니다.

달리기는 어떻습니까 "select last_insert_id();"삽입 후?

MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertInvoice;
comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', "  
    + bookFee + ", " + adminFee + ", " + totalFee + ", " + customerID +  ");";
    + "select last_insert_id();"

int id = Convert.ToInt32(comm.ExecuteScalar());

편집하다: Duffymo가 언급했듯이 매개 변수화 쿼리를 사용하여 잘 제공 될 것입니다. 이와 같이.


편집하다: 매개 변수화 된 버전으로 전환 할 때까지 String.format : Peace를 찾을 수 있습니다.

comm.CommandText = string.Format("{0} '{1}', {2}, {3}, {4}, {5}); select last_insert_id();",
  insertInvoice, invoiceDate.ToString(...), bookFee, adminFee, totalFee, customerID);

다른 팁

MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertStatement;  // Set the insert statement
comm.ExecuteNonQuery();              // Execute the command
long id = comm.LastInsertedId;       // Get the ID of the inserted item

LastInsertedId를 사용하십시오.

여기에서 예제로 내 제안을보십시오. http://livshitz.wordpress.com/2011/10/28/returning-rast-inserted-id-in-c-using-mysql-provider/

데이트를하고 데이터베이스에 문자열로 저장하는 사람을 보게되어 귀찮게합니다. 열 유형에 현실이 반영되지 않는 이유는 무엇입니까?

또한 문자열 연결을 사용하여 SQL 쿼리가 구축되는 것을보고 놀랐습니다. 저는 Java 개발자이고 C#을 전혀 모르지만 도서관 어딘가에 Java.sql.preparedStatement의 라인을 따라 바인딩 메커니즘이 없었는지 궁금합니다. SQL 주입 공격을 방지하는 데 권장됩니다. 또 다른 이점은 SQL을 구문 분석, 검증, 한 번 캐시하고 재사용 할 수 있기 때문에 가능한 성능 이점입니다.

실제로 ExecutesCalar 메소드는 반환중인 데이터 세트의 첫 번째 행의 첫 번째 열을 반환합니다. 귀하의 경우 삽입물 만 수행하고 실제로 데이터를 쿼리하는 것이 아닙니다. 삽입 한 후 (SQL Server의 구문 임계) scope_identity ()를 쿼리해야하며 답변을 얻을 수 있습니다. 여기를 봐:

결합

편집하다: Michael Haren이 지적했듯이, 당신은 당신의 태그에서 mySQL을 사용하고있는 태그에서 언급했습니다. last_insert_id ()를 사용하십시오. scope_identity () 대신;

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top