Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#使用自动增量获取插入id_C#_Mysql_.net_Sql - Fatal编程技术网

C#使用自动增量获取插入id

C#使用自动增量获取插入id,c#,mysql,.net,sql,C#,Mysql,.net,Sql,我正在使用此方法将一行插入表中: MySqlConnection connect = new MySqlConnection(connectionStringMySql); MySqlCommand cmd = new MySqlCommand(); cmd.Connection = connect; cmd.Connection.Open(); string comman

我正在使用此方法将一行插入表中:

            MySqlConnection connect = new MySqlConnection(connectionStringMySql);
            MySqlCommand cmd = new MySqlCommand();

            cmd.Connection = connect;
            cmd.Connection.Open();

            string commandLine = @"INSERT INTO Wanted (clientid,userid,startdate,enddate) VALUES" +
                "(@clientid, @userid, @startdate, @enddate);";
            cmd.CommandText = commandLine;

            cmd.Parameters.AddWithValue("@clientid", userId);
            cmd.Parameters.AddWithValue("@userid", "");
            cmd.Parameters.AddWithValue("@startdate", start);
            cmd.Parameters.AddWithValue("@enddate", end);

            cmd.ExecuteNonQuery();
            cmd.Connection.Close();
我还有一个id列,该列具有
自动增量

我想知道是否有可能获得插入新行时创建的id。

您可以访问MySqlCommand lastinertedid属性

cmd.ExecuteNonQuery();
long id = cmd.LastInsertedId;

基本上,您应该在CommandText的末尾添加以下内容:

SET @newPK = LAST_INSERT_ID();

并添加另一个ADO.NET参数“newPK”。执行命令后,它将包含新的ID。

这就是您想要的吗?不,我想要我的身份证。谢谢你,它工作!!如果我想在一个insert语句中插入多行,那么可以获得每个id吗?谢谢!我读到C#没有这样的属性,所以我正在为此编写一个方法!
MySqlConnection connect = new MySqlConnection(connectionStringMySql);
MySqlCommand cmd = new MySqlCommand();

cmd.Connection = connect;
cmd.Connection.Open();

string commandLine = @"INSERT INTO Wanted (clientid,userid,startdate,enddate) "
    + "VALUES(@clientid, @userid, @startdate, @enddate);";
cmd.CommandText = commandLine;

cmd.Parameters.AddWithValue("@clientid", userId);
**cmd.Parameters["@clientid"].Direction = ParameterDirection.Output;**
cmd.Parameters.AddWithValue("@userid", "");
cmd.Parameters.AddWithValue("@startdate", start);
cmd.Parameters.AddWithValue("@enddate", end);

cmd.ExecuteNonQuery();
cmd.Connection.Close();