Aman Gill
Aman Gill

Reputation: 21

I'm having no error but i can't insert values in database,

I'm trying to get values from I created and the code shows no errors anywhere but the insertion is not working the values are not going in the database. I'm not really at understanding much technical terms because I've just started learning this.

my connection string code

<add name="student_info" connectionString="Data Source=DESKTOP-GH4DT15\MSSQLSERVER01;Initial Catalog=RDO Student info; Integrated Security=True;"/>

this is my insertion code

public bool insert (SchoolClass c)
{
    bool isSuccess = false;
    
    SqlConnection conn = new SqlConnection(mydbconnection);
    DataTable dt = new DataTable();
    try
    {
        string sql = "INSERT INTO student_info (schoolCode, shoolName, schoolOperater, district, taluka, uc, village, nearFamousPlace, studentName, GR, fatherName, CNIC, religion, gender, DOB_date, DOB_month, DOB_year, Address, DOA_date, DOA_month, DOA_year, classAdmitted, currentClass, section, sift, lastSchool, reasonToLeave, parentContact, emergency, DOS_date, DOS_month, DOS_year ) VALUES (@schoolCode, @shoolName, @schoolOperater, @district, @taluka, @uc, @village, @nearFamousPlace, @studentName, @GR, @fatherName, @CNIC, @religion, @gender, @DOB_date, @DOB_month, @DOB_year, @Address, @DOA_date, @DOA_month, @DOA_year, @classAdmitted, @currentClass, @section, @sift, @lastSchool, @reasonToLeave, @parentContact, @emergency, @DOS_date, @DOS_month, @DOS_year)";
        SqlCommand cmd = new SqlCommand(sql, conn);
        conn.Open();
        cmd.Parameters.AddWithValue("@schoolCode", c.schoolCode);
        cmd.Parameters.AddWithValue("@schoolName", c.schoolName);
        cmd.Parameters.AddWithValue("@schoolOperator", c.schoolOperator);
        cmd.Parameters.AddWithValue("@district", c.district);
        cmd.Parameters.AddWithValue("@taluka", c.taluka);
        cmd.Parameters.AddWithValue("@uc", c.uc);
        cmd.Parameters.AddWithValue("@village", c.village);
        cmd.Parameters.AddWithValue("@nearFamousPlace", c.nearFamousPlace);
        cmd.Parameters.AddWithValue("@studentName", c.studentName);
        cmd.Parameters.AddWithValue("@GR", c.GR);
        cmd.Parameters.AddWithValue("@fatherName", c.fatherName);
        cmd.Parameters.AddWithValue("@CNIC", c.CNIC);
        cmd.Parameters.AddWithValue("@religion", c.religion);
        cmd.Parameters.AddWithValue("@gender", c.gender);
        cmd.Parameters.AddWithValue("@DOB_date", c.dob_day);
        cmd.Parameters.AddWithValue("@DOB_month", c.dob_month);
        cmd.Parameters.AddWithValue("@DOB_year", c.dob_year);
        cmd.Parameters.AddWithValue("@Address", c.adress);
        cmd.Parameters.AddWithValue("@DOA_date", c.doa_day);
        cmd.Parameters.AddWithValue("@DOA_month", c.doa_month);
        cmd.Parameters.AddWithValue("@DOA_year", c.doa_year);
        cmd.Parameters.AddWithValue("@classAdmitted", c.classAdmitted);
        cmd.Parameters.AddWithValue("@currentClass", c.currentCalss);
        cmd.Parameters.AddWithValue("@section", c.Section);
        cmd.Parameters.AddWithValue("@shift", c.Sift);
        cmd.Parameters.AddWithValue("@lastSchool", c.lastSchool);
        cmd.Parameters.AddWithValue("@reasonToLeave", c.reasonToLeave);
        cmd.Parameters.AddWithValue("@parentContact", c.parentContact);
        cmd.Parameters.AddWithValue("@emergency", c.emergencyContact);
        cmd.Parameters.AddWithValue("@DOA_date", c.dos_day);
        cmd.Parameters.AddWithValue("@DOA_month", c.dos_month);
        cmd.Parameters.AddWithValue("@DOA_year", c.dos_year);
        
        int row = cmd.ExecuteNonQuery();
        //if successful query then vaule is greater then zero
        if (row > 0)
        {
            isSuccess = true;
        }
        else
        {
            isSuccess = false;
        }
    }
    catch (Exception ex)
    {

    }
    finally
    {
        conn.Close();
    }
    return isSuccess;
}

Upvotes: 0

Views: 766

Answers (2)

yemo1
yemo1

Reputation: 71

Your error is in your connectionstring and the way you call it in your code:

<add name="student_info" connectionString="Data Source=DESKTOP-GH4DT15\MSSQLSERVER01;Initial Catalog=RDO Student info; Integrated Security=True;"/>
  1. Your connectionsting name is student_info
  2. Your database name (initial catalog) should contain no space
  3. Your Data source can just be a period "." provided you're using a local connection and not remote (this is optional though but saves you some keystrokes)

Your calling code is shown below:

using var cn = new SqlConnection(ConnectionString);
using var cmd = new SqlCommand(
            "INSERT INTO ***student_info*** (SchoolName,ParentContact) VALUES (@SchoolName,@ParentContact);SELECT CAST(scope_identity() AS int);", cn);

Note:

  1. Your sql connection is inserting into a wrong Database table (you should probably get an error here)

  2. The best way to store your connection string is in the app.config or appsettings.json file depending on what version of .NET you're using and the call it within your code like so:

    string connectionString = ConfigurationManager.ConnectionStrings["student_info"].ConnectionString;
    

Upvotes: 1

Karen Payne
Karen Payne

Reputation: 5147

one option is to create a class for your data operations. For an insert, use a named value tuple for returning success, an Exception on failure and optionally return the new identifier if you have setup an auto-incrementing column in the table.

The following is enough for seeing how you might consider performing a new record insertion. This code has been written with C#9, .NET Framework Core, if using .NET Framework 4.8 or less some adjustments to the code will be required.

Notes

  • First run your SQL statement in a .sql file (create a new text file in your project with an extension of .sql and Visual Studio will be setup to run the SQL) in Visual Studio or in SSMS (SQL-Server Management Studio) to ensure the statement works outside of your code. Use DECLARE for each parameter passed to the INSERT statement.
  • Validate data passed to the insert method first to ensure there are acceptable values. This may be simple assertion or using data annotation on property of the class.

Base school class (yes it's missing many properties)

public class SchoolClass
{
    public string SchoolName { get; set; }
    public string ParentContact { get; set; }
}

Data operation class

public class Operations
{
    public static string ConnectionString
        => "Data Source=DESKTOP-GH4DT15\\MSSQLSERVER01;Initial Catalog=RDO Student info; Integrated Security=True;";

    /// <summary>
    /// Insert a new record, in this case only enough is done
    /// for you to consider this as one possible methods to
    /// check if the insert worked, if not check the exception
    /// and if worked use the new identifier
    /// </summary>
    /// <param name="schoolClass"></param>
    /// <returns>
    /// Tuple
    ///     success = operation was successful or failed
    ///     exception = if success is false, check exception else use identifier
    ///     identifier = new identifier (assuming auto-incrementing primary column)
    /// </returns>
    public static (bool success, Exception exception, int identifier) InsertRecord(SchoolClass schoolClass)
    {
        try
        {
            using var cn = new SqlConnection(ConnectionString);
            using var cmd = new SqlCommand(
                "INSERT INTO student_info (SchoolName,ParentContact) VALUES (@SchoolName,@ParentContact);SELECT CAST(scope_identity() AS int);", cn);

            cmd.Parameters.Add("@SchoolName", SqlDbType.Text).Value = schoolClass.SchoolName;
            cmd.Parameters.Add("@ParentContact", SqlDbType.Text).Value = schoolClass.ParentContact;
            var id = Convert.ToInt32(cmd.ExecuteScalar());
            cn.Open();
            
            return (true, null, id);
        }
        catch (Exception exception)
        {
            return (false, exception, 0);
        }
    }
    
}

Usage done in a unit test method (which is not really a proper test, just isolating the code from a user interface), replace the Console.WriteLine with a MessageBox and perhaps write to a log file too.

[TestMethod]
public void InsertSchoolRecord()
{
    var schoolRecord = new SchoolClass();

    var (success, exception, identifier) = Operations.InsertRecord(schoolRecord);
    if (success)
    {
        // all is good
    }
    else
    {
        Console.WriteLine(exception.Message);
    }
}

Upvotes: 0

Related Questions