如何连接到 SQL 服务器

How to connect to SQL Server

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

我该如何解决这个问题?

这是我的代码:

控制器:

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;
}

连接是使用连接字符串SqlConnectionclass建立的——这似乎是在你的代码中很好。

BUT:您尝试 插入 值的方式完全错误 - 您需要使用这样的方式:

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();
    }
}