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))+'0104') IF (@ISOweek=0) SET @ISOweek=dbo.ISOweek(CAST(DATEPART(yy,@DATE)-1 AS CHAR(4))+'12'+ 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'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'" + // backUpPath + @"' 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中文網其他相關文章!

C#是微軟在2000年發布的編程語言,旨在結合C 的強大功能和Java的簡潔性。 1.C#是一種類型安全、面向對象的編程語言,支持封裝、繼承和多態。 2.C#的編譯過程將代碼轉化為中間語言(IL),然後在.NET運行時環境(CLR)中即時編譯成機器碼執行。 3.C#的基本用法包括變量聲明、控制流和函數定義,而高級用法涵蓋異步編程、LINQ和委託等。 4.常見錯誤包括類型不匹配和空引用異常,可通過調試器、異常處理和日誌記錄來調試。 5.性能優化建議包括使用LINQ、異步編程和提高代碼可讀性。

C#是一種編程語言,而.NET是一個軟件框架。 1.C#由微軟開發,適用於多平台開發。 2..NET提供類庫和運行時環境,支持多語言。兩者協同工作,構建現代應用。

C#.NET是一個強大的開發平台,結合了C#語言和.NET框架的優勢。 1)它廣泛應用於企業應用、Web開發、遊戲開發和移動應用開發。 2)C#代碼編譯成中間語言後由.NET運行時環境執行,支持垃圾回收、類型安全和LINQ查詢。 3)使用示例包括基本控制台輸出和高級LINQ查詢。 4)常見錯誤如空引用和類型轉換錯誤可以通過調試器和日誌記錄解決。 5)性能優化建議包括異步編程和優化LINQ查詢。 6)儘管面臨競爭,C#.NET通過不斷創新保持其重要地位。

C#.NET的未來趨勢主要集中在雲計算、微服務、AI和機器學習集成以及跨平台開發三個方面。 1)雲計算和微服務:C#.NET通過Azure平台優化雲環境表現,支持構建高效微服務架構。 2)AI和機器學習集成:借助ML.NET庫,C#開發者可在應用中嵌入機器學習模型,推動智能化應用發展。 3)跨平台開發:通過.NETCore和.NET5 ,C#應用可在Windows、Linux和macOS上運行,擴展部署範圍。

C#.NET開發的最新動態和最佳實踐包括:1.異步編程提高應用響應性,使用async和await關鍵字簡化非阻塞代碼;2.LINQ提供強大查詢功能,通過延遲執行和表達式樹高效操作數據;3.性能優化建議包括使用異步編程、優化LINQ查詢、合理管理內存、提升代碼可讀性和維護性、以及編寫單元測試。

如何利用.NET構建應用?使用.NET構建應用可以通過以下步驟實現:1)了解.NET基礎知識,包括C#語言和跨平台開發支持;2)學習核心概念,如.NET生態系統的組件和工作原理;3)掌握基本和高級用法,從簡單控制台應用到復雜的WebAPI和數據庫操作;4)熟悉常見錯誤與調試技巧,如配置和數據庫連接問題;5)應用性能優化與最佳實踐,如異步編程和緩存。

C#在企業級應用、遊戲開發、移動應用和Web開發中均有廣泛應用。 1)在企業級應用中,C#常用於ASP.NETCore開發WebAPI。 2)在遊戲開發中,C#與Unity引擎結合,實現角色控制等功能。 3)C#支持多態性和異步編程,提高代碼靈活性和應用性能。

C#和.NET適用於Web、桌面和移動開發。 1)在Web開發中,ASP.NETCore支持跨平台開發。 2)桌面開發使用WPF和WinForms,適用於不同需求。 3)移動開發通過Xamarin實現跨平台應用。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Dreamweaver CS6
視覺化網頁開發工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。