//mssqlserver public static int GetInsertId(string sql) { try { SqlCommand cmd = new SqlCommand(); using (SqlConnection conn = new SqlConnection(connectionString)) { PrepareCommand(cmd, conn, sql, null); cmd.ExecuteNonQuery(); PrepareCommand(cmd, conn, "Select @@Identity", null); int val = Convert.ToInt32(cmd.ExecuteScalar()); return val; } } catch (Exception err) { throw err; } }private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, string CmdText, SqlTransaction trans) { try { if (conn.State != ConnectionState.Open) { conn.Open(); } cmd.Connection = conn; cmd.CommandText = CmdText; if (trans != null) { cmd.Transaction = trans; } cmd.CommandType = CommandType.Text; } catch (Exception err) { throw err; } }//accesspublic static int GetInsertId(string sql) { try { OleDbCommand cmd = new OleDbCommand(); using (OleDbConnection conn = new OleDbConnection(ConnectionString)) { PrepareCommand(cmd, conn, sql, null); cmd.ExecuteNonQuery(); PrepareCommand(cmd, conn, "Select @@Identity", null); int val =Convert.ToInt32( cmd.ExecuteScalar()); return val; } } catch (Exception err) { throw err; } }public static void PrepareCommand(OleDbCommand cmd, OleDbConnection conn, string CmdText, OleDbTransaction trans) { try { if (conn.State != ConnectionState.Open) { conn.Open(); } cmd.Connection = conn; cmd.CommandText = CmdText; if (trans != null) { cmd.Transaction = trans; } cmd.CommandType = CommandType.Text; } catch (Exception err) { throw err; } }
//还有一种可以用通过插入后查询当前表的最大id的方法获取,但是如果数据并发量大可能回出现问题