백엔드 개발 C#.Net 튜토리얼 csharp에 대한 예제 튜토리얼

csharp에 대한 예제 튜토리얼

Jun 24, 2017 am 10:50 AM
.net c# script

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.Common;//需添加microsoft.sqlserver.connectioninfo.dll的引用
using Microsoft.SqlServer.Management;//
using Microsoft.SqlServer.Management.Smo;//在microsoft.sqlserver.smo.dll中
using Microsoft.SqlServer.Management.Smo.RegisteredServers;//Microsoft.SqlServer.SmoExtended
using Microsoft.SqlServer.Management.Smo.Broker;
using Microsoft.SqlServer.Management.Smo.Agent;
using Microsoft.SqlServer.Management.Smo.SqlEnum;
using Microsoft.SqlServer.Management.Smo.Mail;
using Microsoft.SqlServer.Management.Smo.Internal;
using System.IO;
using System.Data.SqlClient;
using System.Text;
using System.Text.RegularExpressions;

////引用位置: C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\


       /// <summary>
        /// 涂聚文 2017-06-02
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            //Connect to the local, default instance of SQL Server.   
            Microsoft.SqlServer.Management.Common.ServerConnection conn = new ServerConnection(@"GEOVI-BD87B6B9C\GEOVINDU", "geovindu", "888888");
            Server srv = new Server(conn);
            //Reference the AdventureWorks2012 database.   
            Database db = srv.Databases["du"];

            //Define a UserDefinedFunction object variable by supplying the parent database and the name arguments in the constructor.   
            UserDefinedFunction udf = new UserDefinedFunction(db, "IsOWeek");

            //Set the TextMode property to false and then set the other properties.   
            udf.TextMode = false;
            udf.DataType = DataType.Int;
            udf.ExecutionContext = ExecutionContext.Caller;
            udf.FunctionType = UserDefinedFunctionType.Scalar;
            udf.ImplementationType = ImplementationType.TransactSql;

            //Add a parameter.   

            UserDefinedFunctionParameter par = new UserDefinedFunctionParameter(udf, "@DATE", DataType.DateTime);
            udf.Parameters.Add(par);

            //Set the TextBody property to define the user-defined function.   
            udf.TextBody = "BEGIN DECLARE @ISOweek int SET @ISOweek= DATEPART(wk,@DATE)+1 -DATEPART(wk,CAST(DATEPART(yy,@DATE) as CHAR(4))+&#39;0104&#39;) IF (@ISOweek=0) SET @ISOweek=dbo.ISOweek(CAST(DATEPART(yy,@DATE)-1 AS CHAR(4))+&#39;12&#39;+ CAST(24+DATEPART(DAY,@DATE) AS CHAR(2)))+1 IF ((DATEPART(mm,@DATE)=12) AND ((DATEPART(dd,@DATE)-DATEPART(dw,@DATE))>= 28)) SET @ISOweek=1 RETURN(@ISOweek) END;";

            //Create the user-defined function on the instance of SQL Server.   
            udf.Create();

            //Remove the user-defined function.   
           // udf.Drop();  
        }
        /// <summary>
        /// 涂聚文 2017-06-02
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {

                //涂聚文 2017-06-02
                Microsoft.SqlServer.Management.Common.ServerConnection serverconn = new ServerConnection(@"GEOVI-BD87B6B9C\GEOVINDU", "geovindu", "888888");
                string sqlConnectionString = @"Data Source=GEOVI-BD87B6B9C\GEOVINDU;Initial Catalog=Du;User ID=Geovin Du;Password=888888";
                //1.有报错问题
                //FileInfo file = new FileInfo("fu.sql");
                //string script = file.OpenText().ReadToEnd();
                //script = script.Replace("\t", " ").Replace("\n", " ");
                //SqlConnection conn = new SqlConnection(sqlConnectionString);
                //Server server = new Server(serverconn);//new ServerConnection(conn)
                //Database db = server.Databases["du"];
                //server.ConnectionContext.ExecuteNonQuery(script);//出问题

                    SqlConnection conn = new SqlConnection(sqlConnectionString);
                    conn.Open();
                string script = File.ReadAllText("fu.sql");

                    // split script on GO command
                    IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                    foreach (string commandString in commandStrings)
                    {
                        if (commandString.Trim() != "")
                        {
                            new SqlCommand(commandString, conn).ExecuteNonQuery();
                        }
                    }
                    MessageBox.Show("Database updated successfully.");

               
               
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        /// <summary>
        /// Run an .sql script trough sqlcmd.
        /// </summary>
        /// <param name="fileName">the .sql script</param>
        /// <param name="machineName">The name of the server.</param>
        /// <param name="databaseName">The name of the database to connect to.</param>
        /// <param name="trustedConnection">Use a trusted connection.</param>
        /// <param name="args">The arguments passed to the sql script.</param>
        public void RunSqlScript(string fileName, string machineName, string databaseName, bool trustedConnection, string[] args)
        {
            // simple checks
            if (!Path.GetExtension(fileName).Equals(".sql", StringComparison.InvariantCulture))
                throw new Exception("The file doesn&#39;t end with .sql.");

            // check for used arguments
            foreach (var shortArg in new[] { "S", "d", "E", "i" })
            {
                var tmpArg = args.SingleOrDefault(a => a.StartsWith(string.Format("-{0}", shortArg), StringComparison.InvariantCulture));
                if (tmpArg != null)
                    throw new ArgumentException(string.Format("Cannot pass -{0} argument to sqlcmd for a second time.", shortArg));
            }

            // check the params for trusted connection.
            var userArg = args.SingleOrDefault(a => a.StartsWith("-U", StringComparison.InvariantCulture));
            var passwordArg = args.SingleOrDefault(a => a.StartsWith("-P", StringComparison.InvariantCulture));
            if (trustedConnection)
            {
                if (userArg != null)
                    throw new ArgumentException("Cannot pass -H argument when trustedConnection is used.");
                if (passwordArg != null)
                    throw new ArgumentException("Cannot pass -P argument when trustedConnection is used.");
            }
            else
            {
                if (userArg == null)
                    throw new ArgumentException("Exspecting username(-H) argument when trustedConnection is not used.");
                if (passwordArg == null)
                    throw new ArgumentException("Exspecting password(-P) argument when trustedConnection is not used.");
            }


            // set the working directory. (can be needed with ouputfile)
            // TODO: Test if the above statement is correct
            var tmpDirectory = Directory.GetCurrentDirectory();
            var directory = Path.IsPathRooted(fileName) ? Path.GetDirectoryName(fileName) : Path.Combine(fileName);//this.ProjectRoot
            var file = Path.GetFileName(fileName);
            Directory.SetCurrentDirectory(directory);

            // create cmd line
            var cmd = string.Format(string.Format("SQLCMD -S {0} -d {1} -i \"{2}\"", machineName, databaseName, file));
            foreach (var argument in args.Where(a => a.StartsWith("-", StringComparison.InvariantCultureIgnoreCase)))
                cmd += " " + argument;
            if (trustedConnection)
                cmd += " -E";

            // create the process
            var process = new System.Diagnostics.Process();
            process.StartInfo.FileName = "cmd";
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;

            // start the application
            process.Start();
            process.StandardInput.WriteLine("@ECHO OFF");
            process.StandardInput.WriteLine(string.Format("cd {0}", directory));
            process.StandardInput.WriteLine(cmd);
            process.StandardInput.WriteLine("EXIT");
            process.StandardInput.Flush();
            process.WaitForExit();

            // write the output to my debug folder and restore the current directory
           // Debug.Write(process.StandardOutput.ReadToEnd());
            Directory.SetCurrentDirectory(tmpDirectory);
        }

//              public void Restore(OdbcConnection sqlcon, string DatabaseFullPath, string backUpPath)
//           {
//               using (sqlcon)
//               {
//                   string UseMaster = "USE master";
//                   OdbcCommand UseMasterCommand = new OdbcCommand(UseMaster, sqlcon);
//                   UseMasterCommand.ExecuteNonQuery();
//                   // The below query will rollback any transaction which is running on that database and brings SQL Server database in a single user mode.
//                   string Alter1 = @"ALTER DATABASE
//                   [" + DatabaseFullPath + "] SET Single_User WITH Rollback Immediate";
//                   OdbcCommand Alter1Cmd = new OdbcCommand(Alter1, sqlcon);
//                   Alter1Cmd.ExecuteNonQuery();
//                   // The below query will restore database file from disk where backup was taken ....
//                   string Restore = @"RESTORE DATABASE
//                   [" + DatabaseFullPath + "] FROM DISK = N&#39;" +
//                   backUpPath + @"&#39; WITH  FILE = 1,  NOUNLOAD,  STATS = 10";
//                   OdbcCommand RestoreCmd = new OdbcCommand(Restore, sqlcon);
//                   RestoreCmd.ExecuteNonQuery();
//                   // the below query change the database back to multiuser
//                   string Alter2 = @"ALTER DATABASE
//                   [" + DatabaseFullPath + "] SET Multi_User";
//                   OdbcCommand Alter2Cmd = new OdbcCommand(Alter2, sqlcon);
//                   Alter2Cmd.ExecuteNonQuery();
//                   Cursor.Current = Cursors.Default;
//               }
//            }
로그인 후 복사

  





VS 2010 报错:

+ $exception {"混合模式程序集是针对“v2.0.50727”版的运行时生成的,在没有配置其他信息的情况下,无法在 4.0 运行时中加载该程序集。":null} System.Exception {System.IO.FileLoadException}

App.config 配置:

1.一种方式

<startup  useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  <supportedRuntime version="v2.0.50727"/>
</startup>
로그인 후 복사

2.二种方式

<startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0"/>
  </startup>
로그인 후 복사

  

 

 

위 내용은 csharp에 대한 예제 튜토리얼의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

C#을 사용한 Active Directory C#을 사용한 Active Directory Sep 03, 2024 pm 03:33 PM

C#을 사용한 Active Directory 가이드. 여기에서는 소개와 구문 및 예제와 함께 C#에서 Active Directory가 작동하는 방식에 대해 설명합니다.

C#의 액세스 한정자 C#의 액세스 한정자 Sep 03, 2024 pm 03:24 PM

C#의 액세스 수정자에 대한 안내입니다. 예제 및 출력과 함께 C#의 액세스 한정자의 소개 유형에 대해 논의했습니다.

C#의 난수 생성기 C#의 난수 생성기 Sep 03, 2024 pm 03:34 PM

C#의 난수 생성기 가이드입니다. 여기서는 난수 생성기의 작동 방식, 의사 난수 및 보안 숫자의 개념에 대해 설명합니다.

C# 데이터 그리드 보기 C# 데이터 그리드 보기 Sep 03, 2024 pm 03:32 PM

C# 데이터 그리드 뷰 가이드. 여기서는 SQL 데이터베이스 또는 Excel 파일에서 데이터 그리드 보기를 로드하고 내보내는 방법에 대한 예를 설명합니다.

C# 스트링리더 C# 스트링리더 Sep 03, 2024 pm 03:23 PM

C# StringReader에 대한 안내입니다. 여기에서는 C# StringReader에 대한 간략한 개요와 다양한 예제 및 코드와 함께 작동하는 방법에 대해 설명합니다.

C#의 패턴 C#의 패턴 Sep 03, 2024 pm 03:33 PM

C#의 패턴 가이드. 여기에서는 예제 및 코드 구현과 함께 C#의 패턴 소개 및 상위 3가지 유형에 대해 설명합니다.

C# 직렬화 C# 직렬화 Sep 03, 2024 pm 03:30 PM

C# 직렬화 가이드. 여기에서는 C# 직렬화 개체의 소개, 단계, 작업 및 예제를 각각 논의합니다.

C# 스트링라이터 C# 스트링라이터 Sep 03, 2024 pm 03:23 PM

C# StringWriter 가이드. 여기에서는 C# StringWriter 클래스에 대한 간략한 개요와 다양한 예제 및 코드와 함께 작동하는 방법에 대해 설명합니다.

See all articles