-1

I'm having trouble with a SQL Server connection in C#.

My program is simple, input a name and a description, then save it with Active Record in a database. But the data is not begin saved.

When I consult the SQL Server database (Select top 1000 rows), nothing is showing.

What part of the code is not working, the C# or the SQL? I'm using a console command for the inputs.

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

And this is the SQL code

CREATE DATABASE TestDB

USE TestDB

CREATE TABLE Neighborhood 
(
    Name VARCHAR(30) NOT NULL,
    Description VARCHAR(50) NOT NULL,
    CONSTRAINT PK_Neighborhood PRIMARY KEY (Name) 
)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

2

You have a typo here, the correct is @nom:

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

You just forgot to execute the query with 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;
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Charles Cavalcante
  • 1,572
  • 2
  • 14
  • 27