-1

I am writing a sample application to insert data into a SQL Server database using C#. Data is not persisting in the database.

Below is my code:

conn.Open();

SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "Insert into Record (ID,Name) values ('" + txtId.Text + "' , '" + txtName.Text + "')";

cmd.ExecuteNonQuery();
//cmd.Clone();
conn.Close();

The values are not persisted. There is no error when I insert the values. When I changed my command to:

"Insert into Database.dbo.Record (ID,Name) values ('"

it throws an exception:

Incorrect syntax near the keyword 'Database'.

Why is my SQL Server database not being updated?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    Is the name of the table "Record"?... Is there any error message? This is a basic task, you should put some effort into finding the problem. – Galcoholic May 22 '17 at 10:11
  • I haven't done a solution like this using C#, but is it possible that you have to include "database.dbo.Record" as your table, instead of merely "Record" or does the Connection take care of that? – Cenderze May 22 '17 at 10:11
  • 2
    if you trace this code, if you grab the command text, are you sure it is executing? have you run the sql in SQL directly? – BugFinder May 22 '17 at 10:13
  • Please read and act on [mcve]. – philipxy May 22 '17 at 10:40
  • Can you please show us your **connection string**?? – marc_s May 22 '17 at 11:02

1 Answers1

0

Your code as is, is possibly open to SQL injection - you should use parameters.

Also check the table names and primary keys, e.g. if ID is an Identity column it is automatically generated when you insert, so then you'll just INSERT INTO Record (Name) VALUES ('Bob')

Otherwise if ID is a primary key you'll likely have to check you are not trying to insert duplicates.

Please use parameters! (adjust the SqlDbType's if needed)

You should also use a using statement over the connection to properly dispose resources, and ideally use a transaction for updates:

string sqlQuery = "INSERT INTO Record (ID, Name) VALUES (@id, @name); ";

using (SqlConnection conn = new SqlConnection(connectionString)) {
    conn.Open();
    SqlTransaction tran = conn.BeginTransaction();

    try {
        SqlCommand command = new SqlCommand(sqlQuery, conn, tran);

        SqlParameter in1 = command.Parameters.Add("@id", SqlDbType.NVarChar);
        in1.Value = txtId.Text;
        SqlParameter in2 = command.Parameters.Add("@name", SqlDbType.NVarChar);
        in1.Value = txtName.Text;

        command.ExecuteNonQuery();

        tran.Commit();
    } catch (Exception ex) {
        tran.Rollback();    
        //...
    }
}
Kobus
  • 19
  • 4
  • I have tried by this way also. But it is not working. Actually at the running time it is inserted. But whenever I am checking in my database it is not affecting there. Is there anything which I am missing to connect?. And one thing also I am using Microsoft SQL Server Database File (SqlClient) database. – Toshif Khan May 22 '17 at 12:19
  • If you can show how your connection string looks, and the table definition ? – Kobus May 22 '17 at 12:59
  • SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Student.mdf;Integrated Security=True"); this is my connection string. – Toshif Khan May 23 '17 at 04:31
  • I am using service based database in visual studio 2017. And my data source is Microsoft SQL Server Database File (SqlClient). – Toshif Khan May 23 '17 at 04:34
  • System.Data.SqlClient.SqlException: 'An attempt to attach an auto-named database for file C: \Users\MK185299\Documents\Visual Studio 2017\Projects\DatabaseSln\Database\Details.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.' this error it is showing. – Toshif Khan May 23 '17 at 05:05
  • Check out [link](https://msdn.microsoft.com/en-us/library/ms233817.aspx) , specifically the " _Every time I test my application and modify data, my changes are gone the next time I run my application._ " section, maybe that could help. – Kobus May 23 '17 at 07:00