0

i am working on a simple database project in c sharp and ms sql sever 2008 but im having an error upon compiling the program its poping up this message:

The type initializer for 'StudentsInformationSystem.DB_conection' threw an exception

My code:

namespace StudentsInformationSystem
{
    class DB_Access
    {
        private SqlConnection conn;

        public DB_Access()
        {
            conn = DB_conection.GetConnection(); //this is where i am getting the error on this line of code

        }

       public void add_student(string regNo,string fname, string lname, string phoneNo)
       {
            if (conn.State.ToString() == "closed")
            {
                conn.Open();
            }

            SqlCommand newCmd = conn.CreateCommand();
            newCmd.Connection = conn;
            newCmd.CommandType = CommandType.Text;
            newCmd.CommandText = "insert into student values('" + regNo + "','" + fname + "','" + lname + "','" + phoneNo + "')";
            newCmd.ExecuteNonQuery();
        }
    }
}
5
  • 4
    That's not a compiler error. Read the InnerException. Commented Sep 16, 2012 at 16:05
  • im a newbie mind explaining to me what you mean??like InnerException. Commented Sep 16, 2012 at 16:09
  • What error do you get? tell the error sentence please. Most likely it would be something like "connection is not open" is it so? Commented Sep 16, 2012 at 16:14
  • what is db_connection called? i think you need to initialize DB_Connection instance. Commented Sep 16, 2012 at 16:15
  • @MildredShimz: Exceptions occur at execution time. If you're running the code, it must have compiled without error. Compile-time errors are the ones which show up in the Visual Studio "Errors" view, such as if you make a typo and try to use a variable which doesn't exist. Commented Sep 16, 2012 at 16:15

4 Answers 4

3

SQL Injection issues aside, your problem likely comes from comparing ConnectionState to a string.

/* this will never be true because "closed" is not equal to "Closed" */
if (conn.State.ToString() == "closed")
{
   conn.Open();
}

... should be:

if (conn.State == ConnectionState.Closed)
{
    conn.Open();
}

You should also get the connection as close to its usage as possible and never store it as a class-level variable.

using (var conn = DB_conection.GetConnection())
using (var cmd = conn.CreateCommand())
{
    // use conn & cmd

    // they will be closed & disposed of when they leave this block
}
Sign up to request clarification or add additional context in comments.

4 Comments

its still giving me the same problem,i have edited it to show you where exactly im getting the error
@MildredShimz: My answer is still valid for other issues you'll encounter. To adequately answer your question, you'll need to post the code for DB_connection.
As for actually having the DB_connection class at all, please see this answer: stackoverflow.com/a/9707060/4068
im am reposting the question again
0

Supposing that there is no problem with your DB_conection (you have not shared it's details)

Few improvements in the code

public void add_student(string regNo,string fname, string lname, string phoneNo)
{
     if (conn.State == ConnectionSate.Closed)          
            conn.Open();         
     SqlCommand newCmd = conn.CreateCommand();
     newCmd.CommandText = "insert into student values('" + regNo + "','" + fname + "','" + lname + "','" + phoneNo + "')";
     newCmd.ExecuteNonQuery();
}

I will recommend to not close the connection after each query for the sake of quick accessibility of database, and you are already doing this. However after using a data-reader you should close the data-reader, otherwise it could cause some error

//newCmd.Connection = conn; No need you have done this in above statement

//newCmd.CommandType = CommandType.Text; No need, it is by default

Comments

0

Type initializer for [class name] threw an exception.

This indicates an exception raised within the static constructor of a class. You need to check the static constructor of class DB_conection. Its code will be executed before the static method call GetConnection in the code you've shown.

If you run your code in a debugger I'm sure the source of the exception will be obvious.

Comments

0

I dont know if you have fixed the problem since now , but if the application you a writing is from a youtube user tutorial ,

the problem is on the app.confing xml you write at first http://www.youtube.com/watch?list=UL53a-mKN01jQ&v=53a-mKN01jQ&feature=player_detailpage#t=479s

remove the <configSections></configSections>and leave <connectionStrings><add ..</connection Strings> and it should work

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.