Execute SQL script file statements

       General class in the project on the underlying method of executing SQL statements lot, but few provide a method to execute SQL scripts, there was a need for function execution method SQL scripts directly in the project,

Proven project, more practical method, the code will now be posted to share with you:

/// <summary>
        /// 执行SQL语句脚本文件(带注释,带Go)
        /// </summary>
        /// <param name="sqlFileName">sql脚本文件路径</param>
        public static int ExecuteSQLFile(String sqlFileName)
        {
            int icount = 0;
            using (SqlConnection connecction = new SqlConnection(connectionString))
            {
            FileStream stream = new FileStream(sqlFileName, FileMode.Open);
            StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("gb2312"));
                try
                {
                    SqlCommand command = connecction.CreateCommand();
                    connecction.Open();
                    //读取文件
                   
                    StringBuilder builder = new StringBuilder();
                    String strLine = "";
                    while ((strLine = reader.ReadLine()) != null)
                    {
                        if (strLine.Trim().ToUpper() != @"GO")
                        {
                            builder.AppendLine(strLine);
                        }
                        else
                        {
                            command.CommandText = builder.ToString();
                            icount = command.ExecuteNonQuery();
                            builder.Remove(0, builder.Length);
                        }
                    }
                    command.CommandText = builder.ToString();
                    icount = command.ExecuteNonQuery();
                    builder.Remove(0, builder.Length);
                    reader.Close();
                    stream.Close();
                    return icount;
                }
                catch
                {
                    reader.Close();
                    stream.Close();
                    icount = 0;
                    return icount;
                }
            }
        }

 

Reproduced in: https: //www.cnblogs.com/kevinGao/archive/2011/09/23/2186443.html

Guess you like

Origin blog.csdn.net/weixin_34311757/article/details/93053972