我正在尝试将一些数据插入我的数据库(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/