0

私はCシャープとMS SQLサーバー2008で単純なデータベースプロジェクトに取り組んでいますが、プログラムをコンパイルするとエラーが発生し、次のメッセージが表示されます:

「StudentsInformationSystem.DB_conection」の型初期化子が例外をスローしました

私のコード:

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();
        }
    }
}
4

4 に答える 4

3

SQLインジェクションの問題はさておき、問題はConnectionStateを文字列と比較することから発生する可能性があります。

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

...次のようになります:

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

また、接続を可能な限りその使用法に近づけ、クラスレベルの変数として保存しないようにする必要があります。

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
}
于 2012-09-16T16:09:35.517 に答える
0

Type initializer for [class name] threw an exception.

これは、クラスの静的コンストラクター内で発生した例外を示します。クラスの静的コンストラクターを確認する必要がありますDB_conection。そのコードは、表示したコードの静的メソッド呼び出しの前に実行されGetConnectionます。

デバッガーでコードを実行すると、例外の原因が明らかになると確信しています。

于 2012-09-16T16:34:51.913 に答える
0

あなたに問題がないと仮定するとDB_conection(あなたはそれの詳細を共有していません)

コードのいくつかの改善

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();
}

データベースにすばやくアクセスできるようにするために、各クエリの後に接続を閉じないことをお勧めします。すでにこれを行っています。ただし、データリーダーを使用した後は、データリーダーを閉じる必要があります。そうしないと、エラーが発生する可能性があります

//newCmd.Connection = conn; 上記のステートメントでこれを行う必要はありません

//newCmd.CommandType = CommandType.Text; 必要ありません。デフォルトです

于 2012-09-16T16:28:47.407 に答える
0

今から問題を解決したかどうかはわかりませんが、あなたが書いているアプリケーションがYouTubeのユーザーチュートリアルからのものである場合、

問題は、最初に記述する app.confing xml にありますhttp://www.youtube.com/watch?list=UL53a-mKN01jQ&v=53a-mKN01jQ&feature=player_detailpage#t=479s

を削除する<configSections></configSections>and leave <connectionStrings><add ..</connection Strings>と、動作するはずです

于 2012-10-06T19:56:27.733 に答える