首页 > 代码库 > 获取mssqlserver与access数据库插入的当前行的id
获取mssqlserver与access数据库插入的当前行的id
//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的方法获取,但是如果数据并发量大可能回出现问题
获取mssqlserver与access数据库插入的当前行的id
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。