Sql server 如何连接到SQL Server
我正在尝试连接到我的数据库,我是存储库的初学者,依赖注入。我无法连接到数据库 我如何解决这个问题 这是我的代码: 控制器:Sql server 如何连接到SQL Server,sql-server,asp.net-mvc-5,unity-container,repository-pattern,Sql Server,Asp.net Mvc 5,Unity Container,Repository Pattern,我正在尝试连接到我的数据库,我是存储库的初学者,依赖注入。我无法连接到数据库 我如何解决这个问题 这是我的代码: 控制器: public ActionResult Create(FormCollection collection) { try { return RedirectToAction("Index"); } catch { return View(); } } 存储库: public UserMaster
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;
}
公共用户主机添加(用户主机项)
{
使用(SqlConnection sqlCon=newsqlconnection(connectionstring))
{
sqlCon.Open();
string query=“插入员工”
值(@ID、@Name、@City、@Address)”;
对于(int i=0;i而言,连接是使用连接字符串和SqlConnection
类创建的-这在代码中似乎很好
但是:您尝试插入值的方式完全错误-您需要使用以下方法:
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();
}
}
使用(SqlConnection sqlCon=newsqlconnection(connectionstring))
{
sqlCon.Open();
//指定插入的列!
//如果没有@“查询”,则不会被识别为多行字符串…这就是采购订单获取的值在当前上下文中不存在的原因。。。
字符串查询=@“插入员工(ID、姓名、城市、地址)
值(@ID、@Name、@City、@Address)”;
对于(int i=0;i如果您无法实际连接,则可能需要发布您的ConnectionString
(为了安全起见,对详细信息进行了适当修改)。非常感谢,但是当前上下文中不存在插入行抛出错误值。@Ravi只需在字符串引号之前添加一个@符号,编译器就会知道您正在创建一个多行字符串,修改了@符号,但记录不会插入到数据库中。