c# - 无法打开数据库 - 登录请求 - 为什么我无法连接到我的数据库?

标签 c# sql sql-server ado.net connection-string

我正在尝试将一些数据插入我的数据库(Microsoft SQL Server)

我的连接打不开,我收到这条消息:

Cannot open database \"[Sales and Inventory System]\" requested by the login. The login failed.\r\nLogin failed for user 'Mostafa-PC\Mostafa'.

这是我的代码:

public void InsertProduct(List<string> _myName, 
                      List<int> _myAmount, 
                      List<int> _myPrice, string _date)
{
string connectionString = @"Data Source=MOSTAFA-PC;Initial Catalog=[Sales and Inventory System];Integrated Security=True";
string query = @"INSERT INTO dbo.product(Name, Amount, Price, [date]) 
                             VALUES(@Name, @Amount, @Price, @Date);";

using (SqlConnection Con = new SqlConnection(connectionString))
using (SqlCommand Cmd = new SqlCommand(query, Con))
{

    Cmd.Parameters.Add("@Name", SqlDbType.NVarChar);
    Cmd.Parameters.Add("@Amount", SqlDbType.Int);
    Cmd.Parameters.Add("@Price", SqlDbType.Int);
    Cmd.Parameters.Add("@Date", SqlDbType.DateTime).Value = Convert.ToDateTime(_date);

    Cmd.Connection = Con;
    Con.Open();

    int recordsToAdd = _myName.Count();
    for(int x = 0; x < recordsToAdd; x++)
    {
        Cmd.Parameters["@Name"].Value = _myName[x];
        Cmd.Parameters["@Amount"].Value = _myAmount[x];
        Cmd.Parameters["@Price"].Value = _myPrice[x];
        Cmd.ExecuteNonQuery();
    }
}

我已经完成了所有工作,并且到处都进行了搜索。我不明白为什么。

最佳答案

看来您需要检查以下内容才能解决您的错误。

1. 检查权限。 用户必须有权访问此数据库最重要的一个

2. 此外,最好将App.config key 访问到代码端。所以在 app.config 中声明连接字符串并尝试如下设置。

string connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["keyname"]

3. 您还需要尝试在 SSMS 中连接实例,应该不会失败。

Link可以帮助您了解更多信息。

关于c# - 无法打开数据库 - 登录请求 - 为什么我无法连接到我的数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34460699/

相关文章:

c# - 适用于 .Net 的 Azure 服务管理 API

c# - 使用LINQ插入 block 到SQL?

sql - Visual Studio 语法突出显示

sql - Oracle SQL 帮助以两种不同的方式计算相同的事物,但使用共同的分组

sql - 新手应该去哪里获得最好的 SQL 教程资源?

c# - 使用最少的代码从 SQL 数据库行填充文本框

mysql - SSMA 迁移错误

c# - System.ArgumentNullException 使用 botframework 视觉 api

c# - LINQ 从集合 C# 返回 Dictionary<string, List<Item>>

c# - 如何使用 SharpSSH 以编程方式从 SFTP 服务器删除文件?