【问题标题】:How to solve a C# & SQL Server connection problem ? Data is not begin saved如何解决 C# & SQL Server 连接问题?数据未开始保存
【发布时间】:2019-09-27 10:48:52
【问题描述】:

我在使用 C# 连接 SQL Server 时遇到问题。

我的程序很简单,输入名称和描述,然后用 Active Record 将其保存在数据库中。但数据并未开始保存。

当我查询 SQL Server 数据库 (Select top 1000 rows) 时,没有显示任何内容。

代码的哪一部分不起作用,C# 还是 SQL?我正在使用控制台命令进行输入。

我的班级Neighborhood

private string name;
private string description;

public string Name { get { return name; } set { name = value; } }
public string Description { get { return description; } set { description = value; } }

public Neighborhood(string name, string description)
{
    this.Name = name;
    this.Description = description;
}

public Neighborhood(){}

public bool Save()
{
    bool retor = false;
    string strCon = "Data Source=FACUNDO\\USARESTESQLSERVE; Initial Catalog = TestDB; Integrated Security = SSPI; ";

    SqlConnection con = new SqlConnection(strCon);

    string insert = "INSERT INTO Neighborhood (Name, Description) VALUES (@nom, @desc);";

    SqlCommand command = new SqlCommand(insert, con);
    command.Parameters.AddWithValue("@nam", this.Name);
    command.Parameters.AddWithValue("@desc", this.Description);

    try
    {
         con.Open();
         retor = true;
    }
    catch
    {
         retor = false;
         throw;
    }
    finally
    {
         if (con.State == ConnectionState.Open) 
              con.Close();
    }

    return retor;
}

这是 SQL 代码

CREATE DATABASE TestDB

USE TestDB

CREATE TABLE Neighborhood 
(
    Name VARCHAR(30) NOT NULL,
    Description VARCHAR(50) NOT NULL,
    CONSTRAINT PK_Neighborhood PRIMARY KEY (Name) 
)

【问题讨论】:

  • 你在哪里运行SqlCommand
  • 您遇到的错误是什么?你试过什么?帮助我们帮助你
  • 一个错字和一个永远不会被执行的命令。
  • @FacundoFonseca 你有一个错字和一个永远不会执行的命令。
  • 我会先不使用AddWithValue

标签: c# sql-server


【解决方案1】:

你这里有一个错字,正确的是@nom:

command.Parameters.AddWithValue("@nom", this.Name);

您只是忘记使用command.ExecuteNonQuery(); 执行查询:

try
{
   con.Open();

   // execute the query command
   command.ExecuteNonQuery(); 

   retor = true;
}
catch    
{
    retor = false;
    throw;
}
finally 
{
   if (con.State == ConnectionState.Open) 
       con.Close();
}

return retor;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多