ASP.Net MVC控制器操作与ASP.Net Web窗体之间的模拟是否存在差异?在同一个Web项目中使用完全相同的代码,我可以在从Web窗体连接到SQL Server而不是从Controller Action连接到SQL Server时成功模拟Windows用户.以下是我正在测试的代码示例:
string sqlQuery = @"SELECT Top 10 FullName FROM Customer";
// Connect to the database server. You must use Windows Authentication;
SqlConnection connection = new SqlConnection("Data Source=ServerName;Initial Catalog=DBName;Integrated Security=SSPI");
// Create a DataTable to store the results of the query.
DataTable table = new DataTable();
// Create and configure the SQL Data Adapter that will fill the DataTable.
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(sqlQuery, connection);
// Execute the query by filling the …Run Code Online (Sandbox Code Playgroud) 前段时间我为.net应用程序编写了一个ORM层,其中所有数据库行都由一个子类表示DatabaseRecord.有许多的类似方法Load(),Save()在我最初的实现我创建的构造到数据库的连接等等.DatabaseRecord例如,
connection = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString
);
Run Code Online (Sandbox Code Playgroud)
然后我打电话Open(),并Close()在该SQLConnection在我的方法,其访问数据库的开头和结尾.这对我来说(作为熟悉编程但对c#和.net不熟悉的人)是最有效的做事方式 - 有一个连接并在课堂上必要时打开/关闭它.
我刚刚做了一些阅读,似乎在许多地方推荐这种模式:
using (var connection = new SqlConnection(...)) {
connection.Open();
// Stuff with the connection
connection.Close();
}
Run Code Online (Sandbox Code Playgroud)
我可以看到为什么它是可取的 - Dispose()即使您在中间执行的操作导致未捕获的异常,连接也会自动进行.我只是想知道new SqlConnection()像这样可能多次调用的开销是多少.
连接池已启用,因此我认为开销很小,第二种方法应该是最佳实践,但我只是想确保我的假设是正确的.
使用SQLCommand/ SQLConnection而不是OleDbCommand/ 是否有所不同OleDbConnection.从API舒适性,功能,性能或安全性角度来看,我是否从中获得了任何优势?还是其他任何观点?
我有以下代码。对 connection.OpenAsync() 的调用会毫无例外地退出程序。甚至调用方方法上的 finally 也不会被调用。程序针对.NET45 知道吗?
更新:这是与 .Wait() 一起使用的父代码。当在下面的子方法中调用 connection.OpenAsync() 时,它会在父代码中没有 .Wait() 的情况下退出。
static void Main(string[] args)
{
UpdateSqlDatabase updateSqlDatabase = new UpdateSqlDatabase(args);
updateSqlDatabase.UpdateDatabaseSchemaAsync().Wait();
}
Run Code Online (Sandbox Code Playgroud)
在一系列异步方法调用之后:
public async Task<T> ExecuteQueryAsync<T>(string connectionString, string commandText, IDictionary<string, object> parameters, Func<SqlDataReader, T> rowMapFunc)
{
using (var connection = new SqlConnection(connectionString))
{
try
{
await connection.OpenAsync();
}
catch (Exception ex)
{
}
SqlCommand command = connection.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = commandText;
if (parameters != null)
{
foreach (var item in parameters)
{
command.Parameters.AddWithValue(item.Key, item.Value); …Run Code Online (Sandbox Code Playgroud) 我试图只使用一个连接并一起运行两个命令,一个使用事务,一个不使用.
没有跟踪/日志记录功能,因为此解决方案部署在另一个位置.因此,当流程部分失败时,我至少可以按照日志进行操作.
我将在这里添加我的测试代码:
SqlConnection connection = GetConnection();
SqlTransaction transaction = null;
try
{
connection.Open();
transaction = connection.BeginTransaction();
SqlCommand logCommand = new SqlCommand("Log before main command", connection);
logCommand.ExecuteNonQuery();
string sql = "SELECT 1";
SqlCommand command = new SqlCommand(sql, connection, transaction);
int rows = command.ExecuteNonQuery();
logCommand = new SqlCommand("Log after main command", connection);
logCommand.ExecuteNonQuery();
// Other similar code
transaction.Commit();
command.Dispose();
}
catch { /* Rollback etc */ }
finally { /* etc */ }
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
当分配给命令的连接处于挂起的本地事务中时,ExecuteNonQuery要求命令具有事务.该命令的Transaction属性尚未初始化.
如果没有其他无交易连接,有没有办法实现我想要做的事情?
或者,如果有一个更好的建议,以不同的方式通过单个连接优化我的代码,我就可以开始学习它.
SQLConnection 使用随机命名管道(445) 而不是tcp(1433)。命名管道端口被我们的防火墙阻止,但 tcp 未被阻止。仅当尝试连接到我们的 SQL 服务器之一时才会发生这种情况。大多数时候应用程序使用 TCP,但随机尝试使用命名管道端口。我们的 sql 连接非常简单,我们没有做任何花哨的事情。
\n\n我们不想在连接字符串上硬编码 TCP 端口。我们已经尝试过并且解决了问题。该问题仅在上周出现,并且我们尝试连接的 Web 应用程序已运行一段时间。
\n\n为什么sql连接有时会尝试连接445而不是1433?这是 .net 最新更新引入的错误还是服务器可以指定要使用的下一个端口?
\n\n更新 2016-09-23 11:00
\n\n这是我们用于连接的代码示例
\n\nstring connectionString = "Data Source=SERVERNAME;Initial Catalog=DATABASE;uid=username;pwd=mypass;MultipleActiveResultSets=True";\nusing (SqlConnection connection = new SqlConnection(connectionString))\n{\n try {\n connection.Open(); \n\xe2\x80\xa6\nRun Code Online (Sandbox Code Playgroud)\n 我遇到了一个奇怪的问题,我可以通过调用存储过程返回结果,但代码追溯失败.
public IEnumerable<T> ExecuteStoredProcedure<T>(string storedProcedureName, IDataMapper<T> mapper, IDictionary<string, object> parameters)
{
using (var connection = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(storedProcedureName, connection))
{
cmd.CommandType = CommandType.StoredProcedure;
foreach (var key in parameters.Keys)
{
cmd.Parameters.AddWithValue(key, parameters[key]);
}
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
//return MapRecordsToDTOs(reader, mapper);
//let's test:
IEnumerable<T> result = MapRecordsToDTOs(reader, mapper);
var x = (new List<T>(result)).Count;
System.Diagnostics.Debug.WriteLine(x);
return result;
}
}
}
private static IEnumerable<T> MapRecordsToDTOs<T>(SqlDataReader reader, IDataMapper<T> mapper)
{
if (reader.HasRows)
{
while (reader.Read())
{
System.Diagnostics.Debug.WriteLine(reader["Id"]); //what's …Run Code Online (Sandbox Code Playgroud) 我使用带有队列触发器的 Azure Functions 来处理部分工作负载。特定函数查询数据库,这会产生扩展问题,因为大量并发函数实例 ping 数据库会导致 Azrue DB 连接的最大允许数量不断受到影响。
本文https://learn.microsoft.com/en-us/azure/azure-functions/manage-connections将 HttpClient 列为应设为静态的资源之一。是否也应该使用静态 SqlConnection 将数据库访问设为静态来解决此问题,或者通过保留常量连接对象会导致其他问题吗?
static sqlconnection azure azure-sql-database azure-functions
我当前正在映射网络驱动器并以这种方式连接到文件 (Z:\Data\Database.db)。我希望能够在连接字符串中使用相对路径 (\server\Data\Database.db),但它给了我一个 SQLite 错误“无法打开数据库文件”。检查Directory.Exists(\\server\Data\Database.db);返回 true。
以下是使用路径“\\server”作为参数打开连接的尝试:
public static OpenDB(string dbPath)
{
using (SQLiteConnection conn = new SQLiteConnection($"Data Source={Path.Combine(dbPath, "Data\\Database.db")}"))
{
if (dbPath != null && dbPath != "")
{
try
{
conn.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Unable to Open Database", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
Run Code Online (Sandbox Code Playgroud) 我在我的应用程序中看到持续的死锁,即使它不执行 select 语句、delete 语句和 update 语句。它只是插入全新的数据。
TL;DR:这似乎与外键有关。如果我删除它,那么我根本不会遇到任何死锁。但由于显而易见的原因,这不是一个可接受的解决方案。
鉴于下表结构
CREATE TABLE [dbo].[IncomingFile]
(
[Id] UNIQUEIDENTIFIER NOT NULL,
[ConcurrencyVersion] RowVersion NOT NULL,
CONSTRAINT [PK_IncomingFile] PRIMARY KEY CLUSTERED([Id])
)
GO
CREATE TABLE [dbo].[IncomingFileEvent]
(
[Id] UNIQUEIDENTIFIER NOT NULL,
[ConcurrencyVersion] RowVersion NOT NULL,
[IncomingFileId] UNIQUEIDENTIFIER NOT NULL,
CONSTRAINT [PK_IncomingFileEvent] PRIMARY KEY CLUSTERED([Id]),
CONSTRAINT [FK_IncomingFileEvent_IncomingFileId]
FOREIGN KEY ([IncomingFileId])
REFERENCES [dbo].[IncomingFile] ([Id])
)
GO
Run Code Online (Sandbox Code Playgroud)
当我遇到多个并发任务插入数据时,我总是看到一个死锁。READ_COMMITTED_SNAPSHOT在我的数据库选项中启用(即使我没有阅读)。
这是将重现该问题的代码。如果您没有遇到问题,请增加NumberOfTasksPerCpu程序顶部的常量。
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace …Run Code Online (Sandbox Code Playgroud) sqlconnection ×10
c# ×6
.net ×3
sql-server ×2
ado.net ×1
asp.net ×1
asp.net-mvc ×1
async-await ×1
asynchronous ×1
azure ×1
database ×1
idisposable ×1
oledb ×1
sqlcommand ×1
sqlite ×1
static ×1
using ×1
webforms ×1