【问题标题】:How to connect to SQL Server如何连接到 SQL Server
【发布时间】:2019-10-06 10:04:17
【问题描述】:

我正在尝试连接到我的数据库,我是存储库的初学者,依赖注入。我无法连接到数据库。

我该如何解决这个问题?

这是我的代码:

控制器:

public ActionResult Create(FormCollection collection)
{
    try
    {
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

存储库:

public UserMaster Add(UserMaster item)
{
    using (SqlConnection sqlCon = new SqlConnection(connectionstring))
    {
        sqlCon.Open();
        string query = "INSERT INTO Employee 
                        VALUES (@ID, @Name, @City, @Address)";

        for (int i = 0; i <= 100; i++)
        {
            SqlCommand sqlcmd = new SqlCommand(query, sqlCon);

            sqlcmd.Parameters.AddWithValue(ID = i, Name = "newride", City = "newride", Address = "USA");
        }
    }

    return item;
}

【问题讨论】:

  • 如果您无法真正连接,您可能需要发布您的ConnectionString(为安全起见,详细信息已适当修改)。

标签: sql-server asp.net-mvc-5 unity-container repository-pattern


【解决方案1】:

connection 是使用 connection stringSqlConnection 类创建的 - 在您的代码中似乎没问题。

但是:您尝试插入值的方式都是错误的 - 您需要使用这样的东西:

using (SqlConnection sqlCon = new SqlConnection(connectionstring))
{
    sqlCon.Open();
    // SPECIFY the column you insert into!
    // Without the @ "query" is not recognized as a multiline string... that's why the PO is getting that VALUES does not exists in the current context...
    string query = @"INSERT INTO Employee (ID, Name, City, Address)
                    VALUES (@ID, @Name, @City, @Address)";

    for (int i = 0; i <= 100; i++)
    {
        SqlCommand sqlcmd = new SqlCommand(query, sqlCon);

        // set the individual parameters, and AVOID "AddWithValue"
        sqlcmd.Parameters.Add("@ID", SqlDbType.Int).Value = i;
        sqlcmd.Parameters.Add("@Name", SqlDbType.VarChar, 100).Value = "newride";
        sqlcmd.Parameters.Add("@City", SqlDbType.VarChar, 100).Value = "newride";
        sqlcmd.Parameters.Add("@Address", SqlDbType.VarChar, 100).Value = "USA";

        // and then *EXECUTE* the SqlCommand to actually RUN the INSERT
        sqlcmd.ExecuteNonQuery();
    }
}

【讨论】:

  • 非常感谢,但当前上下文中不存在插入行抛出错误值。
  • @Ravi 只需在字符串引号前加一个@符号,编译器就会知道你在那儿创建了一个多行字符串
  • 修改了@符号但记录没有插入数据库。
猜你喜欢
  • 1970-01-01
  • 2013-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多