.net一次连接执行多条sql语句

方法一:

   string SQLString="select 1; select 2;";

   using (OdbcConnection connection = new OdbcConnection(connectionString))
            {
                using (OdbcCommand cmd = new OdbcCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (OdbcException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }

 

方法二:

  List<string> sqls = new List<string>();
                sqls.Add("select 1;");
                sqls.Add("select 2;");

  using (OdbcConnection conn = new OdbcConnection(connectionString))
            {
                conn.Open();
                OdbcCommand cmd = new OdbcCommand();
                cmd.Connection = conn;
                OdbcTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    int count = 0;
                    for (int n = 0; n < SQLStringList.Count; n++)
                    {
                        string strsql = SQLStringList[n];
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            count += cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                    return count;
                }
                catch
                {
                    tx.Rollback();
                    return 0;
                }
            }

个人认为第二种方法较合适。

.net一次连接执行多条sql语句,布布扣,bubuko.com

.net一次连接执行多条sql语句

上一篇:命令行下从bak文件恢复sqlserver数据库方法


下一篇:Oracle Enterprise Manager 11g 输入用户名和口令 点击“登录”按键后没反应,也不报错,是什么原因?