Click here to view and discuss this page in DocCommentXchange. In the future, you will be sent there automatically.
以下示例显示如何获得为新插入行所生成的主键。在本示例中,将使用 SACommand 对象调用 SQL 存储过程和 SAParameter 对象以对其返回的主键进行检索。出于演示的目的,本示例将创建一个示例表 (adodotnet_primarykey) 和用于插入行和返回主键值的存储过程 (sp_adodotnet_primarykey)。
SAConnection conn = new SAConnection( "Data Source=SQL Anywhere 12 Demo" ); conn.Open(); SACommand cmd = conn.CreateCommand(); cmd.CommandText = "CREATE TABLE IF NOT EXISTS adodotnet_primarykey (" + "ID INTEGER DEFAULT AUTOINCREMENT, " + "Name CHAR(40) )"; cmd.ExecuteNonQuery(); cmd.CommandText = "CREATE or REPLACE PROCEDURE sp_adodotnet_primarykey(" + "out p_id int, in p_name char(40) )" + "BEGIN " + "INSERT INTO adodotnet_primarykey( name ) VALUES( p_name );" + "SELECT @@IDENTITY INTO p_id;" + "END"; cmd.ExecuteNonQuery(); cmd.CommandText = "sp_adodotnet_primarykey"; cmd.CommandType = CommandType.StoredProcedure; SAParameter parmId = new SAParameter(); parmId.SADbType = SADbType.Integer; parmId.Direction = ParameterDirection.Output; cmd.Parameters.Add(parmId); SAParameter parmName = new SAParameter(); parmName.SADbType = SADbType.Char; parmName.Direction = ParameterDirection.Input; cmd.Parameters.Add(parmName); parmName.Value = "R & D --- Command"; cmd.ExecuteNonQuery(); int id1 = (int)parmId.Value; System.Console.WriteLine("Primary key=" + id1); parmName.Value = "Marketing --- Command"; cmd.ExecuteNonQuery(); int id2 = (int)parmId.Value; System.Console.WriteLine("Primary key=" + id2); parmName.Value = "Sales --- Command"; cmd.ExecuteNonQuery(); int id3 = (int)parmId.Value; System.Console.WriteLine("Primary key=" + id3); parmName.Value = "Shipping --- Command"; cmd.ExecuteNonQuery(); int id4 = (int)parmId.Value; System.Console.WriteLine("Primary key=" + id4); cmd.CommandText = "SELECT * FROM adodotnet_primarykey"; cmd.CommandType = CommandType.Text; SADataReader dr = cmd.ExecuteReader(); while (dr.Read()) { System.Console.WriteLine(dr.GetString(0) + ", " + dr.GetString(1)); } dr.Close(); conn.Close();