SQL连接的最佳实践是什么?
目前我正在使用以下内容:
using (SqlConnection sqlConn = new SqlConnection(CONNECTIONSTRING))
{
sqlConn.Open();
// DB CODE GOES HERE
}
Run Code Online (Sandbox Code Playgroud)
我已经读过这是一种非常有效的SQL连接方式.默认情况下,SQL池是活动的,所以我理解的是,当using代码结束时,SqlConnection对象被关闭并处理,但是与DB的实际连接放在SQL连接池中.我错了吗?
这个让我难过.我甚至没有尝试连接数据库.当这段代码到达我实例化一个新的SqlConnection对象的行时,它就会挂起,而不是抛出异常或任何东西.我试过为2.0编译它.3.5和4.0,他们都挂了.当然它也适用于我的机器和你的机器.但我正在尝试在Windows Server 2008 x64服务器上运行此代码,它不会让步.
// example.cs
using System;
using System.Data;
using System.Data.SqlClient;
public class MainClass {
public static void Main(string[] args) {
Console.WriteLine("start");
SqlConnection conn = new SqlConnection(); // hangs here
Console.WriteLine("finish"); // never makes it here.
}
}
Run Code Online (Sandbox Code Playgroud)
编译(2.0):c:\ Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe example.cs
尝试从我的C#应用程序中打开数据库连接时,我看到以下错误.我意识到这个错误可能已经出现在100个问题之前.但是,在这种情况下,错误仅出现在我的特定台式PC上运行的C#应用程序上.我通过Google和本网站浏览了互联网,但我找不到解决方案.
错误:
"建立与SQL Server的连接时发生与网络相关或特定于实例的错误.未找到服务器或无法访问服务器.验证实例名称是否正确以及SQL Server是否配置为允许远程连接.(提供程序:命名管道提供程序,错误:40 - 无法打开与SQL Server的连接)"
为什么这个场景是独一无二的:
我能够从SQL Server Management Studio(SSMS)连接到SQL服务器.此应用程序在另一台计算机上工作,并能够从那里建立到SQL服务器的连接.因此,此错误方案特定于在我的特定台式PC上运行的C#应用程序.其他应用程序工作(SSMS).其他PC的工作.
当我使用WireShark"嗅探线路"时,跟踪显示我的应用程序正在尝试通过NamedPipes连接(即\ Server\IPC $).我似乎无法强迫它使用TCP/IP.
我试过的事:
我错过了什么吗?
这是连接字符串我试过...
Data Source=<servername>;Initial Catalog=HIE;Integrated Security=true
Server=tcp:10.240.11.81;Integrated Security=SSPI; database=HIE
Data Source=10.240.11.81,1433;Network Library=DBMSSOCN;Initial Catalog=HIE;User ID=<SqlUserIdThatISetUpAsSysAdmin>;Password=<password>
Run Code Online (Sandbox Code Playgroud)
这是代码片段:
_conn = new SqlConnection(); // _conn declared globally
_conn.ConnectionString = <the connection string above>;
_conn.Open();
Run Code Online (Sandbox Code Playgroud) 在C#中,可以通过在连接字符串中使用"Pooling = True"和"Max Pool Size = XY"来启用/禁用连接池.
如:sql连接字符串中"Max Pool Size"的最大允许值是多少
是否可以通过编程方式询问SQL Server的连接数是多少以及当前的池大小是多少?
出于性能考虑,我正在使用SqlConnection并从SQL Server数据库SqlReaderStream返回一个byte[] 流:
private static SqlConnection GetConnection()
{
var sqlConnectionStringBuilder =
new SqlConnectionStringBuilder(
ConfigurationManager.ConnectionStrings["StudentsSystemEntities"].ConnectionString)
{
Pooling = true
};
var connection = new SqlConnection(sqlConnectionStringBuilder.ConnectionString);
connection.Open();
return connection;
}
public FileDownloadModel GetFileById(Guid fileId)
{
var connection = GetConnection();
var command = new SqlCommand(
@"SELECT [FileSize], [FileExtension], [Content] FROM [dbo].[Files] WHERE [FileId] = @fileId;",
connection);
var paramFilename = new SqlParameter(@"fileId", SqlDbType.UniqueIdentifier) { Value = fileId };
command.Parameters.Add(paramFilename);
var reader = command.ExecuteReader(
CommandBehavior.SequentialAccess | CommandBehavior.SingleResult
| …Run Code Online (Sandbox Code Playgroud) 如何在执行.Net应用程序期间始终保持SqlConnection(或使用其他组件)打开(连接)?
我需要这个,因为我的应用程序需要使用此commnad进行检测
exec sp_who2
Run Code Online (Sandbox Code Playgroud)
我的应用程序的多少个实例连接到mydatabase,以限制访问(许可证控制).
例
A)我的应用程序从location1执行
exec sp_who2 B)我的应用程序从location2执行
exec sp_who2 对不起我的英语不好.
提前致谢.
我使用using语句SqlConnection.它对性能有好处,因为强制调用Dispose()会更快地释放与池的连接.
但是,我意识到在使用中创建的对象无法重新定义.我不能这样做:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
//...
connection = new SqlConnection(connectionString2);
//...
connection = new SqlConnection(connectionString3);
}
Run Code Online (Sandbox Code Playgroud)
我想知道我是否可以替换使用,并做这样的事情:
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
//...
connection = new SqlConnection(connectionString2);
//...
connection = new SqlConnection(connectionString3);
}
Run Code Online (Sandbox Code Playgroud)
该SqlConnection不会是最后一次入店后}梅开二度.当对象超出范围时,Dispose()会立即被调用吗?
使用s时如何固定证书SqlConnection?从SqlConnection的连接字符串参数关键词和价值观,我知道我可以设置Encrypted到true强制(鼓励?)使用SSL/TLS的.
但是,为了固定证书,我相信我们需要使用ServerCertificateValidationCallbackfrom ServicePointManager(下面的示例代码由ArneVajhøj提供HTTP/HTTPS).我不清楚如何接通PinCertificate(从ServicePointManager)到SqlConnection.
更新:在microsoft.public.dotnet.languages.csharp上与ArneVajhøj交谈,似乎无法对连接进行所需的控制.Vajhøj提供了一个指向加密SQL Server连接的链接.
public static void Main(string[] args)
{
ServicePointManager.ServerCertificateValidationCallback = PinCertificate;
WebRequest wr = WebRequest.Create("https://www.google.com/");
wr.GetResponse();
}
public static bool PinCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
byte[] chash = certificate.GetCertHash();
StringBuilder sb = new StringBuilder(chash.Length * 2);
foreach (byte b in chash)
sb.AppendFormat("{0:X2}", b);
// Verify against known SHA1 thumb print of the certificate
String …Run Code Online (Sandbox Code Playgroud) 当我连接它时会出错
无法识别的转义序列.
NEPOLEON\ADMN HERE ON THIS SLASH. NEPOLEON\ADMN IS MY SQL SERVER NAME.
SqlConnection con = new SqlConnection("Server=NEPOLEON\ADMN;Database=MASTER;Trusted_Connection=True");
Run Code Online (Sandbox Code Playgroud) 我试图使用CryptUnprotectData读取使用密码保护的CryptProtectData进入SecureString,并用它来连接到数据库.我可以输出正确的密码,但尝试创建新的密码SqlConnection失败后出现以下情况:
System.TypeInitializationException was unhandled
HResult=-2146233036
Message=The type initializer for 'System.Data.SqlClient.SqlConnection' threw an exception.
Source=System.Data
TypeName=System.Data.SqlClient.SqlConnection
StackTrace:
at System.Data.SqlClient.SqlConnection..ctor()
at System.Data.SqlClient.SqlConnection..ctor(String connectionString, SqlCredential credential)
at System.Data.SqlClient.SqlConnection..ctor(String connectionString)
at ProtectedSqlTest.Program.Main() in C:\Git\ProtectedSqlTest\ProtectedSqlTest\Program.cs:line 16
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object …Run Code Online (Sandbox Code Playgroud) c# ×10
sqlconnection ×10
.net ×2
sql-server ×2
.net-2.0 ×1
ado.net ×1
asp.net-mvc ×1
count ×1
filestream ×1
http ×1
named-pipes ×1
pinvoke ×1
scope ×1
securestring ×1
sql ×1
ssl ×1
winforms ×1