zoukankan      html  css  js  c++  java
  • SqlCommand.ExecuteScalar

    下面的示例创建一个 SqlCommand,然后使用 ExecuteScalar 执行它。向该示例传递两个字符串,一个字符串表示要插入到表中的新值,另一个字符串用于连接至数据源。如果已插入新行,则此函数会返回新的“Identity”列值,如果失败,则返回 0。

    static public int AddProductCategory(string newName, string connString)
    {
        Int32 newProdID = 0;
        string sql =
            "INSERT INTO Production.ProductCategory (Name) VALUES (@Name); "
            + "SELECT CAST(scope_identity() AS int)";
        using (SqlConnection conn = new SqlConnection(connString))
        {
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.Add("@Name", SqlDbType.VarChar);
            cmd.Parameters["@name"].Value = newName;
            try
            {
                conn.Open();
                newProdID = (Int32)cmd.ExecuteScalar();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        return (int)newProdID;
    }
    
    
    
  • 相关阅读:
    一条SQL的执行流程
    LinkedList源码解析
    MinorGC前检查
    AbstractList源码分析
    JVM常用命令
    CountDownLatch源码解析
    ReentrantLock源码解析
    HTTPS简单介绍
    工厂方法模式
    观察者模式
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/1728888.html
Copyright © 2011-2022 走看看