MySQL插入数据获得自动增长的ID

INSERT INTO data(name) Values(@name); SELECT @@Identity
/// <summary>
/// 插入一个用户返回自动增长的id
/// </summary>
/// <param name="userInfo"></param>
/// <returns></returns>
public int Add(UserInfo userInfo)
{
    //string sql = "insert into " + JDBCConst.UserInfoDB + " value(NULL,@cardId,@username,@password,@role)";
    // 插入一个用户返回自动增长的id
    string sql = "insert into " + JDBCConst.UserInfoDB + " value(NULL,@cardId,@username,@password,@role,null);SELECT @@Identity";
    
    MySqlParameter parCardId = new MySqlParameter("@CardId", userInfo.card_id);
    MySqlParameter parUsername = new MySqlParameter("@username", userInfo.username);
    MySqlParameter parPassword = new MySqlParameter("@password", userInfo.password);
    MySqlParameter parRole = new MySqlParameter("@role", userInfo.role);
    object i;
    try
    {
        i = Utils.ExecuteScalar(sql,parCardId,parUsername,parPassword,parRole);
    }
    catch (Exception)
    {
        throw;
    }
   
    int k = Convert.ToInt32(i);

    return k;
}
posted @ 2020-12-29 14:23  大海&  阅读(3374)  评论(0编辑  收藏  举报